├── .gitignore ├── .mvn └── wrapper │ ├── MavenWrapperDownloader.java │ ├── maven-wrapper.jar │ └── maven-wrapper.properties ├── README.md ├── mvnw ├── mvnw.cmd ├── pom.xml └── src ├── main ├── java │ └── com │ │ └── xjt │ │ └── proxy │ │ ├── MysqlProxyApplication.java │ │ ├── aop │ │ └── DataSourceConfig.java │ │ ├── common │ │ └── MyMapper.java │ │ ├── controller │ │ └── UserController.java │ │ ├── domain │ │ └── User.java │ │ ├── dynamicdatasource │ │ ├── DataSourceContextAop.java │ │ ├── DataSourceContextHolder.java │ │ ├── DataSourceSelector.java │ │ ├── DynamicDataSource.java │ │ └── DynamicDataSourceEnum.java │ │ ├── mapper │ │ └── UserMapper.java │ │ └── service │ │ └── UserService.java └── resources │ ├── application.yml │ ├── logback-spring.xml │ ├── mapper │ └── UserMapper.xml │ └── sql │ └── user.sql └── test └── java └── com └── xjt └── proxy ├── MysqlProxyApplicationTests.java └── service └── UserServiceTest.java /.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | target/ 3 | !.mvn/wrapper/maven-wrapper.jar 4 | !**/src/main/** 5 | !**/src/test/** 6 | 7 | ### STS ### 8 | .apt_generated 9 | .classpath 10 | .factorypath 11 | .project 12 | .settings 13 | .springBeans 14 | .sts4-cache 15 | 16 | ### IntelliJ IDEA ### 17 | .idea 18 | *.iws 19 | *.iml 20 | *.ipr 21 | 22 | ### NetBeans ### 23 | /nbproject/private/ 24 | /nbbuild/ 25 | /dist/ 26 | /nbdist/ 27 | /.nb-gradle/ 28 | build/ 29 | 30 | ### VS Code ### 31 | .vscode/ 32 | -------------------------------------------------------------------------------- /.mvn/wrapper/MavenWrapperDownloader.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | * Copyright 2012-2019 the original author or authors. 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with 6 | * the License. You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on 11 | * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the 12 | * specific language governing permissions and limitations under the License. 13 | */ 14 | import java.net.*; 15 | import java.io.*; 16 | import java.nio.channels.*; 17 | import java.util.Properties; 18 | 19 | public class MavenWrapperDownloader { 20 | 21 | private static final String WRAPPER_VERSION = "0.5.5"; 22 | /** 23 | * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. 24 | */ 25 | private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/" 26 | + WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar"; 27 | 28 | /** 29 | * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to use instead of the 30 | * default one. 31 | */ 32 | private static final String MAVEN_WRAPPER_PROPERTIES_PATH = ".mvn/wrapper/maven-wrapper.properties"; 33 | 34 | /** 35 | * Path where the maven-wrapper.jar will be saved to. 36 | */ 37 | private static final String MAVEN_WRAPPER_JAR_PATH = ".mvn/wrapper/maven-wrapper.jar"; 38 | 39 | /** 40 | * Name of the property which should be used to override the default download url for the wrapper. 41 | */ 42 | private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; 43 | 44 | public static void main(String args[]) { 45 | System.out.println("- Downloader started"); 46 | File baseDirectory = new File(args[0]); 47 | System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); 48 | 49 | // If the maven-wrapper.properties exists, read it and check if it contains a custom 50 | // wrapperUrl parameter. 51 | File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); 52 | String url = DEFAULT_DOWNLOAD_URL; 53 | if (mavenWrapperPropertyFile.exists()) { 54 | FileInputStream mavenWrapperPropertyFileInputStream = null; 55 | try { 56 | mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); 57 | Properties mavenWrapperProperties = new Properties(); 58 | mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); 59 | url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); 60 | } catch (IOException e) { 61 | System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); 62 | } finally { 63 | try { 64 | if (mavenWrapperPropertyFileInputStream != null) { 65 | mavenWrapperPropertyFileInputStream.close(); 66 | } 67 | } catch (IOException e) { 68 | // Ignore ... 69 | } 70 | } 71 | } 72 | System.out.println("- Downloading from: " + url); 73 | 74 | File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); 75 | if (!outputFile.getParentFile().exists()) { 76 | if (!outputFile.getParentFile().mkdirs()) { 77 | System.out.println( 78 | "- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'"); 79 | } 80 | } 81 | System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); 82 | try { 83 | downloadFileFromURL(url, outputFile); 84 | System.out.println("Done"); 85 | System.exit(0); 86 | } catch (Throwable e) { 87 | System.out.println("- Error downloading"); 88 | e.printStackTrace(); 89 | System.exit(1); 90 | } 91 | } 92 | 93 | private static void downloadFileFromURL(String urlString, File destination) throws Exception { 94 | if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) { 95 | String username = System.getenv("MVNW_USERNAME"); 96 | char[] password = System.getenv("MVNW_PASSWORD").toCharArray(); 97 | Authenticator.setDefault(new Authenticator() { 98 | @Override 99 | protected PasswordAuthentication getPasswordAuthentication() { 100 | return new PasswordAuthentication(username, password); 101 | } 102 | }); 103 | } 104 | URL website = new URL(urlString); 105 | ReadableByteChannel rbc; 106 | rbc = Channels.newChannel(website.openStream()); 107 | FileOutputStream fos = new FileOutputStream(destination); 108 | fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); 109 | fos.close(); 110 | rbc.close(); 111 | } 112 | 113 | } 114 | -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Taoxj/mysql-proxy/64f48834c71ebf555ddc538d3c447340f6bce118/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.2/apache-maven-3.6.2-bin.zip 2 | wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.5/maven-wrapper-0.5.5.jar 3 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | 本篇博客为该项目的详细介绍,看完后觉得不错的同学记得给个star哦! 3 | 4 | ### 前言 5 | 6 | 相信有经验的同学都清楚,当db的读写量过高时,我们会备份一份或多份的从库用于做数据的读取,然后主库就主要承担写入的功能(也有读取需要,但压力不大),当db分好主从库后,我们还需要在项目实现自动连接主从库,达到读写分离的效果。实现读写分离并不困难,只要在数据库连接池手动控制好对应的db服务地址即可,但那样就会侵入业务代码,而且一个项目操作数据库的地方可能很多,如果都手动控制的话无疑会是很大的工作量,对此,我们有必要改造出一套方便的工具。 7 | 8 | 以Java语言来说,如今大部分的项目都是基于Spring Boot框架来搭建项目架构的,结合Spring本身自带的AOP工具,我们可以很容易就构建能实现读写分离效果的注解类,用注解的话可以达到对业务代码无入侵的效果,而且使用上也比较方便。 9 | 10 | 下面就简单带大家写个demo。 11 | 12 | ### 环境部署 13 | 14 | 数据库:MySql 15 | 16 | 库数量:2个,一主一从 17 | 18 | 关于mysql的主从环境部署之前已经写过文章介绍过了,这里就不再赘述,参考[《windows版的mysql主从复制环境搭建》](https://www.cnblogs.com/yeya/p/11878009.html) 19 | 20 | ### 开始项目 21 | 22 | 首先,毫无疑问,先开始搭建一个SpringBoot工程,然后在pom文件中引入如下依赖: 23 | 24 | ``` 25 | 26 | 27 | com.alibaba 28 | druid-spring-boot-starter 29 | 1.1.10 30 | 31 | 32 | org.mybatis.spring.boot 33 | mybatis-spring-boot-starter 34 | 1.3.2 35 | 36 | 37 | tk.mybatis 38 | mapper-spring-boot-starter 39 | 2.1.5 40 | 41 | 42 | mysql 43 | mysql-connector-java 44 | 8.0.16 45 | 46 | 47 | 48 | org.springframework.boot 49 | spring-boot-starter-jdbc 50 | provided 51 | 52 | 53 | org.springframework.boot 54 | spring-boot-starter-aop 55 | provided 56 | 57 | 58 | 59 | org.springframework.boot 60 | spring-boot-starter-web 61 | 62 | 63 | org.projectlombok 64 | lombok 65 | true 66 | 67 | 68 | com.alibaba 69 | fastjson 70 | 1.2.4 71 | 72 | 73 | org.springframework.boot 74 | spring-boot-starter-test 75 | test 76 | 77 | 78 | org.springframework.boot 79 | spring-boot-starter-data-jpa 80 | 81 | 82 | ``` 83 | 84 | #### 目录结构 85 | 86 | 引入基本的依赖后,整理一下目录结构,完成后的项目骨架大致如下: 87 | 88 | ![](https://img2018.cnblogs.com/blog/1478697/201911/1478697-20191126160006909-1194392322.png) 89 | 90 | #### 建表 91 | 92 | 创建一张表user,在主库执行sql语句同时在从库生成对应的表数据 93 | 94 | ``` 95 | DROP TABLE IF EXISTS `user`; 96 | CREATE TABLE `user` ( 97 | `user_id` bigint(20) NOT NULL COMMENT '用户id', 98 | `user_name` varchar(255) DEFAULT '' COMMENT '用户名称', 99 | `user_phone` varchar(50) DEFAULT '' COMMENT '用户手机', 100 | `address` varchar(255) DEFAULT '' COMMENT '住址', 101 | `weight` int(3) NOT NULL DEFAULT '1' COMMENT '权重,大者优先', 102 | `created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', 103 | `updated_at` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', 104 | PRIMARY KEY (`user_id`) 105 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8; 106 | 107 | INSERT INTO `user` VALUES ('1196978513958141952', '测试1', '18826334748', '广州市海珠区', '1', '2019-11-20 10:28:51', '2019-11-22 14:28:26'); 108 | INSERT INTO `user` VALUES ('1196978513958141953', '测试2', '18826274230', '广州市天河区', '2', '2019-11-20 10:29:37', '2019-11-22 14:28:14'); 109 | INSERT INTO `user` VALUES ('1196978513958141954', '测试3', '18826273900', '广州市天河区', '1', '2019-11-20 10:30:19', '2019-11-22 14:28:30'); 110 | ``` 111 | 112 | 113 | #### 主从数据源配置 114 | 115 | 116 | application.yml,主要信息是主从库的数据源配置 117 | 118 | ``` 119 | server: 120 | port: 8001 121 | spring: 122 | jackson: 123 | date-format: yyyy-MM-dd HH:mm:ss 124 | time-zone: GMT+8 125 | datasource: 126 | type: com.alibaba.druid.pool.DruidDataSource 127 | driver-class-name: com.mysql.cj.jdbc.Driver 128 | master: 129 | url: jdbc:mysql://127.0.0.1:3307/user?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&failOverReadOnly=false&useSSL=false&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true 130 | username: root 131 | password: 132 | slave: 133 | url: jdbc:mysql://127.0.0.1:3308/user?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&failOverReadOnly=false&useSSL=false&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true 134 | username: root 135 | password: 136 | ``` 137 | 138 | 因为有一主一从两个数据源,我们用枚举类来代替,方便我们使用时能对应 139 | 140 | ``` 141 | @Getter 142 | public enum DynamicDataSourceEnum { 143 | MASTER("master"), 144 | SLAVE("slave"); 145 | private String dataSourceName; 146 | DynamicDataSourceEnum(String dataSourceName) { 147 | this.dataSourceName = dataSourceName; 148 | } 149 | } 150 | ``` 151 | 152 | 数据源配置信息类 **DataSourceConfig**,这里配置了两个数据源,masterDb和slaveDb 153 | 154 | ``` 155 | @Configuration 156 | @MapperScan(basePackages = "com.xjt.proxy.mapper", sqlSessionTemplateRef = "sqlTemplate") 157 | public class DataSourceConfig { 158 | 159 | // 主库 160 | @Bean 161 | @ConfigurationProperties(prefix = "spring.datasource.master") 162 | public DataSource masterDb() { 163 | return DruidDataSourceBuilder.create().build(); 164 | } 165 | 166 | /** 167 | * 从库 168 | */ 169 | @Bean 170 | @ConditionalOnProperty(prefix = "spring.datasource", name = "slave", matchIfMissing = true) 171 | @ConfigurationProperties(prefix = "spring.datasource.slave") 172 | public DataSource slaveDb() { 173 | return DruidDataSourceBuilder.create().build(); 174 | } 175 | 176 | /** 177 | * 主从动态配置 178 | */ 179 | @Bean 180 | public DynamicDataSource dynamicDb(@Qualifier("masterDb") DataSource masterDataSource, 181 | @Autowired(required = false) @Qualifier("slaveDb") DataSource slaveDataSource) { 182 | DynamicDataSource dynamicDataSource = new DynamicDataSource(); 183 | Map targetDataSources = new HashMap<>(); 184 | targetDataSources.put(DynamicDataSourceEnum.MASTER.getDataSourceName(), masterDataSource); 185 | if (slaveDataSource != null) { 186 | targetDataSources.put(DynamicDataSourceEnum.SLAVE.getDataSourceName(), slaveDataSource); 187 | } 188 | dynamicDataSource.setTargetDataSources(targetDataSources); 189 | dynamicDataSource.setDefaultTargetDataSource(masterDataSource); 190 | return dynamicDataSource; 191 | } 192 | @Bean 193 | public SqlSessionFactory sessionFactory(@Qualifier("dynamicDb") DataSource dynamicDataSource) throws Exception { 194 | SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); 195 | bean.setMapperLocations( 196 | new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/*Mapper.xml")); 197 | bean.setDataSource(dynamicDataSource); 198 | return bean.getObject(); 199 | } 200 | @Bean 201 | public SqlSessionTemplate sqlTemplate(@Qualifier("sessionFactory") SqlSessionFactory sqlSessionFactory) { 202 | return new SqlSessionTemplate(sqlSessionFactory); 203 | } 204 | @Bean(name = "dataSourceTx") 205 | public DataSourceTransactionManager dataSourceTx(@Qualifier("dynamicDb") DataSource dynamicDataSource) { 206 | DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager(); 207 | dataSourceTransactionManager.setDataSource(dynamicDataSource); 208 | return dataSourceTransactionManager; 209 | } 210 | } 211 | ``` 212 | 213 | #### 设置路由 214 | 215 | 设置路由的目的为了方便查找对应的数据源,我们可以用ThreadLocal保存数据源的信息到每个线程中,方便我们需要时获取 216 | 217 | ``` 218 | public class DataSourceContextHolder { 219 | private static final ThreadLocal DYNAMIC_DATASOURCE_CONTEXT = new ThreadLocal<>(); 220 | public static void set(String datasourceType) { 221 | DYNAMIC_DATASOURCE_CONTEXT.set(datasourceType); 222 | } 223 | public static String get() { 224 | return DYNAMIC_DATASOURCE_CONTEXT.get(); 225 | } 226 | public static void clear() { 227 | DYNAMIC_DATASOURCE_CONTEXT.remove(); 228 | } 229 | } 230 | ``` 231 | 232 | 获取路由 233 | 234 | ``` 235 | public class DynamicDataSource extends AbstractRoutingDataSource { 236 | @Override 237 | protected Object determineCurrentLookupKey() { 238 | return DataSourceContextHolder.get(); 239 | } 240 | } 241 | ``` 242 | 243 | AbstractRoutingDataSource的作用是基于查找key路由到对应的数据源,它内部维护了一组目标数据源,并且做了路由key与目标数据源之间的映射,提供基于key查找数据源的方法。 244 | 245 | #### 数据源的注解 246 | 247 | 为了可以方便切换数据源,我们可以写一个注解,注解中包含数据源对应的枚举值,默认是主库, 248 | 249 | ``` 250 | @Retention(RetentionPolicy.RUNTIME) 251 | @Target(ElementType.METHOD) 252 | @Documented 253 | public @interface DataSourceSelector { 254 | 255 | DynamicDataSourceEnum value() default DynamicDataSourceEnum.MASTER; 256 | boolean clear() default true; 257 | } 258 | ``` 259 | 260 | #### aop切换数据源 261 | 262 | 到这里,aop终于可以现身出场了,这里我们定义一个aop类,对有注解的方法做切换数据源的操作,具体代码如下: 263 | 264 | ``` 265 | @Slf4j 266 | @Aspect 267 | @Order(value = 1) 268 | @Component 269 | public class DataSourceContextAop { 270 | 271 | @Around("@annotation(com.xjt.proxy.dynamicdatasource.DataSourceSelector)") 272 | public Object setDynamicDataSource(ProceedingJoinPoint pjp) throws Throwable { 273 | boolean clear = true; 274 | try { 275 | Method method = this.getMethod(pjp); 276 | DataSourceSelector dataSourceImport = method.getAnnotation(DataSourceSelector.class); 277 | clear = dataSourceImport.clear(); 278 | DataSourceContextHolder.set(dataSourceImport.value().getDataSourceName()); 279 | log.info("========数据源切换至:{}", dataSourceImport.value().getDataSourceName()); 280 | return pjp.proceed(); 281 | } finally { 282 | if (clear) { 283 | DataSourceContextHolder.clear(); 284 | } 285 | 286 | } 287 | } 288 | private Method getMethod(JoinPoint pjp) { 289 | MethodSignature signature = (MethodSignature)pjp.getSignature(); 290 | return signature.getMethod(); 291 | } 292 | 293 | } 294 | ``` 295 | 296 | 到这一步,我们的准备配置工作就完成了,下面开始测试效果。 297 | 298 | 先写好Service文件,包含读取和更新两个方法, 299 | 300 | ``` 301 | @Service 302 | public class UserService { 303 | 304 | @Autowired 305 | private UserMapper userMapper; 306 | 307 | @DataSourceSelector(value = DynamicDataSourceEnum.MASTER) 308 | public int update(Long userId) { 309 | User user = new User(); 310 | user.setUserId(userId); 311 | user.setUserName("老薛"); 312 | return userMapper.updateByPrimaryKeySelective(user); 313 | } 314 | 315 | @DataSourceSelector(value = DynamicDataSourceEnum.SLAVE) 316 | public User find(Long userId) { 317 | User user = new User(); 318 | user.setUserId(userId); 319 | return userMapper.selectByPrimaryKey(user); 320 | } 321 | } 322 | ``` 323 | 324 | 根据方法上的注解可以看出,读的方法走从库,更新的方法走主库,更新的对象是userId为`1196978513958141952` 的数据, 325 | 326 | 然后我们写个测试类测试下是否能达到效果, 327 | 328 | ``` 329 | @RunWith(SpringRunner.class) 330 | @SpringBootTest 331 | class UserServiceTest { 332 | 333 | @Autowired 334 | UserService userService; 335 | 336 | @Test 337 | void find() { 338 | User user = userService.find(1196978513958141952L); 339 | System.out.println("id:" + user.getUserId()); 340 | System.out.println("name:" + user.getUserName()); 341 | System.out.println("phone:" + user.getUserPhone()); 342 | } 343 | 344 | @Test 345 | void update() { 346 | Long userId = 1196978513958141952L; 347 | userService.update(userId); 348 | User user = userService.find(userId); 349 | System.out.println(user.getUserName()); 350 | } 351 | } 352 | ``` 353 | 354 | 测试结果: 355 | 356 | 1、读取方法 357 | 358 | ![](https://img2020.cnblogs.com/blog/1478697/202103/1478697-20210308011010913-474866408.png) 359 | 360 | 2、更新方法 361 | 362 | ![](https://img2020.cnblogs.com/blog/1478697/202103/1478697-20210308011019315-236391720.png) 363 | 364 | 执行之后,比对数据库就可以发现主从库都修改了数据,说明我们的读写分离是成功的。当然,更新方法可以指向从库,这样一来就只会修改到从库的数据,而不会涉及到主库。 365 | 366 | ### 注意 367 | 368 | 上面测试的例子虽然比较简单,但也符合常规的读写分离配置。值得说明的是,读写分离的作用是为了缓解写库,也就是主库的压力,但一定要基于数据一致性的原则,就是保证主从库之间的数据一定要一致。**如果一个方法涉及到写的逻辑,那么该方法里所有的数据库操作都要走主库**。 369 | 370 | 假设写的操作执行完后数据有可能还没同步到从库,然后读的操作也开始执行了,如果这个读取的程序走的依然是从库的话,那么就会出现数据不一致的现象了,这是我们不允许的。 371 | 372 | -------------------------------------------------------------------------------- /mvnw: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # ---------------------------------------------------------------------------- 3 | # Licensed to the Apache Software Foundation (ASF) under one 4 | # or more contributor license agreements. See the NOTICE file 5 | # distributed with this work for additional information 6 | # regarding copyright ownership. The ASF licenses this file 7 | # to you under the Apache License, Version 2.0 (the 8 | # "License"); you may not use this file except in compliance 9 | # with the License. You may obtain a copy of the License at 10 | # 11 | # https://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, 14 | # software distributed under the License is distributed on an 15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | # KIND, either express or implied. See the License for the 17 | # specific language governing permissions and limitations 18 | # under the License. 19 | # ---------------------------------------------------------------------------- 20 | 21 | # ---------------------------------------------------------------------------- 22 | # Maven2 Start Up Batch script 23 | # 24 | # Required ENV vars: 25 | # ------------------ 26 | # JAVA_HOME - location of a JDK home dir 27 | # 28 | # Optional ENV vars 29 | # ----------------- 30 | # M2_HOME - location of maven2's installed home dir 31 | # MAVEN_OPTS - parameters passed to the Java VM when running Maven 32 | # e.g. to debug Maven itself, use 33 | # set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 34 | # MAVEN_SKIP_RC - flag to disable loading of mavenrc files 35 | # ---------------------------------------------------------------------------- 36 | 37 | if [ -z "$MAVEN_SKIP_RC" ] ; then 38 | 39 | if [ -f /etc/mavenrc ] ; then 40 | . /etc/mavenrc 41 | fi 42 | 43 | if [ -f "$HOME/.mavenrc" ] ; then 44 | . "$HOME/.mavenrc" 45 | fi 46 | 47 | fi 48 | 49 | # OS specific support. $var _must_ be set to either true or false. 50 | cygwin=false; 51 | darwin=false; 52 | mingw=false 53 | case "`uname`" in 54 | CYGWIN*) cygwin=true ;; 55 | MINGW*) mingw=true;; 56 | Darwin*) darwin=true 57 | # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home 58 | # See https://developer.apple.com/library/mac/qa/qa1170/_index.html 59 | if [ -z "$JAVA_HOME" ]; then 60 | if [ -x "/usr/libexec/java_home" ]; then 61 | export JAVA_HOME="`/usr/libexec/java_home`" 62 | else 63 | export JAVA_HOME="/Library/Java/Home" 64 | fi 65 | fi 66 | ;; 67 | esac 68 | 69 | if [ -z "$JAVA_HOME" ] ; then 70 | if [ -r /etc/gentoo-release ] ; then 71 | JAVA_HOME=`java-config --jre-home` 72 | fi 73 | fi 74 | 75 | if [ -z "$M2_HOME" ] ; then 76 | ## resolve links - $0 may be a link to maven's home 77 | PRG="$0" 78 | 79 | # need this for relative symlinks 80 | while [ -h "$PRG" ] ; do 81 | ls=`ls -ld "$PRG"` 82 | link=`expr "$ls" : '.*-> \(.*\)$'` 83 | if expr "$link" : '/.*' > /dev/null; then 84 | PRG="$link" 85 | else 86 | PRG="`dirname "$PRG"`/$link" 87 | fi 88 | done 89 | 90 | saveddir=`pwd` 91 | 92 | M2_HOME=`dirname "$PRG"`/.. 93 | 94 | # make it fully qualified 95 | M2_HOME=`cd "$M2_HOME" && pwd` 96 | 97 | cd "$saveddir" 98 | # echo Using m2 at $M2_HOME 99 | fi 100 | 101 | # For Cygwin, ensure paths are in UNIX format before anything is touched 102 | if $cygwin ; then 103 | [ -n "$M2_HOME" ] && 104 | M2_HOME=`cygpath --unix "$M2_HOME"` 105 | [ -n "$JAVA_HOME" ] && 106 | JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 107 | [ -n "$CLASSPATH" ] && 108 | CLASSPATH=`cygpath --path --unix "$CLASSPATH"` 109 | fi 110 | 111 | # For Mingw, ensure paths are in UNIX format before anything is touched 112 | if $mingw ; then 113 | [ -n "$M2_HOME" ] && 114 | M2_HOME="`(cd "$M2_HOME"; pwd)`" 115 | [ -n "$JAVA_HOME" ] && 116 | JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" 117 | fi 118 | 119 | if [ -z "$JAVA_HOME" ]; then 120 | javaExecutable="`which javac`" 121 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then 122 | # readlink(1) is not available as standard on Solaris 10. 123 | readLink=`which readlink` 124 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then 125 | if $darwin ; then 126 | javaHome="`dirname \"$javaExecutable\"`" 127 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" 128 | else 129 | javaExecutable="`readlink -f \"$javaExecutable\"`" 130 | fi 131 | javaHome="`dirname \"$javaExecutable\"`" 132 | javaHome=`expr "$javaHome" : '\(.*\)/bin'` 133 | JAVA_HOME="$javaHome" 134 | export JAVA_HOME 135 | fi 136 | fi 137 | fi 138 | 139 | if [ -z "$JAVACMD" ] ; then 140 | if [ -n "$JAVA_HOME" ] ; then 141 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 142 | # IBM's JDK on AIX uses strange locations for the executables 143 | JAVACMD="$JAVA_HOME/jre/sh/java" 144 | else 145 | JAVACMD="$JAVA_HOME/bin/java" 146 | fi 147 | else 148 | JAVACMD="`which java`" 149 | fi 150 | fi 151 | 152 | if [ ! -x "$JAVACMD" ] ; then 153 | echo "Error: JAVA_HOME is not defined correctly." >&2 154 | echo " We cannot execute $JAVACMD" >&2 155 | exit 1 156 | fi 157 | 158 | if [ -z "$JAVA_HOME" ] ; then 159 | echo "Warning: JAVA_HOME environment variable is not set." 160 | fi 161 | 162 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher 163 | 164 | # traverses directory structure from process work directory to filesystem root 165 | # first directory with .mvn subdirectory is considered project base directory 166 | find_maven_basedir() { 167 | 168 | if [ -z "$1" ] 169 | then 170 | echo "Path not specified to find_maven_basedir" 171 | return 1 172 | fi 173 | 174 | basedir="$1" 175 | wdir="$1" 176 | while [ "$wdir" != '/' ] ; do 177 | if [ -d "$wdir"/.mvn ] ; then 178 | basedir=$wdir 179 | break 180 | fi 181 | # workaround for JBEAP-8937 (on Solaris 10/Sparc) 182 | if [ -d "${wdir}" ]; then 183 | wdir=`cd "$wdir/.."; pwd` 184 | fi 185 | # end of workaround 186 | done 187 | echo "${basedir}" 188 | } 189 | 190 | # concatenates all lines of a file 191 | concat_lines() { 192 | if [ -f "$1" ]; then 193 | echo "$(tr -s '\n' ' ' < "$1")" 194 | fi 195 | } 196 | 197 | BASE_DIR=`find_maven_basedir "$(pwd)"` 198 | if [ -z "$BASE_DIR" ]; then 199 | exit 1; 200 | fi 201 | 202 | ########################################################################################## 203 | # Extension to allow automatically downloading the maven-wrapper.jar from Maven-central 204 | # This allows using the maven wrapper in projects that prohibit checking in binary data. 205 | ########################################################################################## 206 | if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then 207 | if [ "$MVNW_VERBOSE" = true ]; then 208 | echo "Found .mvn/wrapper/maven-wrapper.jar" 209 | fi 210 | else 211 | if [ "$MVNW_VERBOSE" = true ]; then 212 | echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." 213 | fi 214 | if [ -n "$MVNW_REPOURL" ]; then 215 | jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.5/maven-wrapper-0.5.5.jar" 216 | else 217 | jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.5/maven-wrapper-0.5.5.jar" 218 | fi 219 | while IFS="=" read key value; do 220 | case "$key" in (wrapperUrl) jarUrl="$value"; break ;; 221 | esac 222 | done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" 223 | if [ "$MVNW_VERBOSE" = true ]; then 224 | echo "Downloading from: $jarUrl" 225 | fi 226 | wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" 227 | if $cygwin; then 228 | wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"` 229 | fi 230 | 231 | if command -v wget > /dev/null; then 232 | if [ "$MVNW_VERBOSE" = true ]; then 233 | echo "Found wget ... using wget" 234 | fi 235 | if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then 236 | wget "$jarUrl" -O "$wrapperJarPath" 237 | else 238 | wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" 239 | fi 240 | elif command -v curl > /dev/null; then 241 | if [ "$MVNW_VERBOSE" = true ]; then 242 | echo "Found curl ... using curl" 243 | fi 244 | if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then 245 | curl -o "$wrapperJarPath" "$jarUrl" -f 246 | else 247 | curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f 248 | fi 249 | 250 | else 251 | if [ "$MVNW_VERBOSE" = true ]; then 252 | echo "Falling back to using Java to download" 253 | fi 254 | javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" 255 | # For Cygwin, switch paths to Windows format before running javac 256 | if $cygwin; then 257 | javaClass=`cygpath --path --windows "$javaClass"` 258 | fi 259 | if [ -e "$javaClass" ]; then 260 | if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then 261 | if [ "$MVNW_VERBOSE" = true ]; then 262 | echo " - Compiling MavenWrapperDownloader.java ..." 263 | fi 264 | # Compiling the Java class 265 | ("$JAVA_HOME/bin/javac" "$javaClass") 266 | fi 267 | if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then 268 | # Running the downloader 269 | if [ "$MVNW_VERBOSE" = true ]; then 270 | echo " - Running MavenWrapperDownloader.java ..." 271 | fi 272 | ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") 273 | fi 274 | fi 275 | fi 276 | fi 277 | ########################################################################################## 278 | # End of extension 279 | ########################################################################################## 280 | 281 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} 282 | if [ "$MVNW_VERBOSE" = true ]; then 283 | echo $MAVEN_PROJECTBASEDIR 284 | fi 285 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" 286 | 287 | # For Cygwin, switch paths to Windows format before running java 288 | if $cygwin; then 289 | [ -n "$M2_HOME" ] && 290 | M2_HOME=`cygpath --path --windows "$M2_HOME"` 291 | [ -n "$JAVA_HOME" ] && 292 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` 293 | [ -n "$CLASSPATH" ] && 294 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"` 295 | [ -n "$MAVEN_PROJECTBASEDIR" ] && 296 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` 297 | fi 298 | 299 | # Provide a "standardized" way to retrieve the CLI args that will 300 | # work with both Windows and non-Windows executions. 301 | MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" 302 | export MAVEN_CMD_LINE_ARGS 303 | 304 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 305 | 306 | exec "$JAVACMD" \ 307 | $MAVEN_OPTS \ 308 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ 309 | "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ 310 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" 311 | -------------------------------------------------------------------------------- /mvnw.cmd: -------------------------------------------------------------------------------- 1 | @REM ---------------------------------------------------------------------------- 2 | @REM Licensed to the Apache Software Foundation (ASF) under one 3 | @REM or more contributor license agreements. See the NOTICE file 4 | @REM distributed with this work for additional information 5 | @REM regarding copyright ownership. The ASF licenses this file 6 | @REM to you under the Apache License, Version 2.0 (the 7 | @REM "License"); you may not use this file except in compliance 8 | @REM with the License. You may obtain a copy of the License at 9 | @REM 10 | @REM https://www.apache.org/licenses/LICENSE-2.0 11 | @REM 12 | @REM Unless required by applicable law or agreed to in writing, 13 | @REM software distributed under the License is distributed on an 14 | @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | @REM KIND, either express or implied. See the License for the 16 | @REM specific language governing permissions and limitations 17 | @REM under the License. 18 | @REM ---------------------------------------------------------------------------- 19 | 20 | @REM ---------------------------------------------------------------------------- 21 | @REM Maven2 Start Up Batch script 22 | @REM 23 | @REM Required ENV vars: 24 | @REM JAVA_HOME - location of a JDK home dir 25 | @REM 26 | @REM Optional ENV vars 27 | @REM M2_HOME - location of maven2's installed home dir 28 | @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands 29 | @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending 30 | @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven 31 | @REM e.g. to debug Maven itself, use 32 | @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 33 | @REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files 34 | @REM ---------------------------------------------------------------------------- 35 | 36 | @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' 37 | @echo off 38 | @REM set title of command window 39 | title %0 40 | @REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' 41 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% 42 | 43 | @REM set %HOME% to equivalent of $HOME 44 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") 45 | 46 | @REM Execute a user defined script before this one 47 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre 48 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending 49 | if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" 50 | if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" 51 | :skipRcPre 52 | 53 | @setlocal 54 | 55 | set ERROR_CODE=0 56 | 57 | @REM To isolate internal variables from possible post scripts, we use another setlocal 58 | @setlocal 59 | 60 | @REM ==== START VALIDATION ==== 61 | if not "%JAVA_HOME%" == "" goto OkJHome 62 | 63 | echo. 64 | echo Error: JAVA_HOME not found in your environment. >&2 65 | echo Please set the JAVA_HOME variable in your environment to match the >&2 66 | echo location of your Java installation. >&2 67 | echo. 68 | goto error 69 | 70 | :OkJHome 71 | if exist "%JAVA_HOME%\bin\java.exe" goto init 72 | 73 | echo. 74 | echo Error: JAVA_HOME is set to an invalid directory. >&2 75 | echo JAVA_HOME = "%JAVA_HOME%" >&2 76 | echo Please set the JAVA_HOME variable in your environment to match the >&2 77 | echo location of your Java installation. >&2 78 | echo. 79 | goto error 80 | 81 | @REM ==== END VALIDATION ==== 82 | 83 | :init 84 | 85 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn". 86 | @REM Fallback to current working directory if not found. 87 | 88 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% 89 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir 90 | 91 | set EXEC_DIR=%CD% 92 | set WDIR=%EXEC_DIR% 93 | :findBaseDir 94 | IF EXIST "%WDIR%"\.mvn goto baseDirFound 95 | cd .. 96 | IF "%WDIR%"=="%CD%" goto baseDirNotFound 97 | set WDIR=%CD% 98 | goto findBaseDir 99 | 100 | :baseDirFound 101 | set MAVEN_PROJECTBASEDIR=%WDIR% 102 | cd "%EXEC_DIR%" 103 | goto endDetectBaseDir 104 | 105 | :baseDirNotFound 106 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR% 107 | cd "%EXEC_DIR%" 108 | 109 | :endDetectBaseDir 110 | 111 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig 112 | 113 | @setlocal EnableExtensions EnableDelayedExpansion 114 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a 115 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% 116 | 117 | :endReadAdditionalConfig 118 | 119 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" 120 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" 121 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 122 | 123 | set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.5/maven-wrapper-0.5.5.jar" 124 | 125 | FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( 126 | IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B 127 | ) 128 | 129 | @REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central 130 | @REM This allows using the maven wrapper in projects that prohibit checking in binary data. 131 | if exist %WRAPPER_JAR% ( 132 | if "%MVNW_VERBOSE%" == "true" ( 133 | echo Found %WRAPPER_JAR% 134 | ) 135 | ) else ( 136 | if not "%MVNW_REPOURL%" == "" ( 137 | SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.5/maven-wrapper-0.5.5.jar" 138 | ) 139 | if "%MVNW_VERBOSE%" == "true" ( 140 | echo Couldn't find %WRAPPER_JAR%, downloading it ... 141 | echo Downloading from: %DOWNLOAD_URL% 142 | ) 143 | 144 | powershell -Command "&{"^ 145 | "$webclient = new-object System.Net.WebClient;"^ 146 | "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ 147 | "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ 148 | "}"^ 149 | "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ 150 | "}" 151 | if "%MVNW_VERBOSE%" == "true" ( 152 | echo Finished downloading %WRAPPER_JAR% 153 | ) 154 | ) 155 | @REM End of extension 156 | 157 | @REM Provide a "standardized" way to retrieve the CLI args that will 158 | @REM work with both Windows and non-Windows executions. 159 | set MAVEN_CMD_LINE_ARGS=%* 160 | 161 | %MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* 162 | if ERRORLEVEL 1 goto error 163 | goto end 164 | 165 | :error 166 | set ERROR_CODE=1 167 | 168 | :end 169 | @endlocal & set ERROR_CODE=%ERROR_CODE% 170 | 171 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost 172 | @REM check for post script, once with legacy .bat ending and once with .cmd ending 173 | if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" 174 | if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" 175 | :skipRcPost 176 | 177 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' 178 | if "%MAVEN_BATCH_PAUSE%" == "on" pause 179 | 180 | if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% 181 | 182 | exit /B %ERROR_CODE% 183 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.springframework.boot 7 | spring-boot-starter-parent 8 | 2.2.1.RELEASE 9 | 10 | 11 | com.xjt 12 | proxy 13 | 0.0.1-SNAPSHOT 14 | mysql-proxy 15 | mysql-proxy 16 | 17 | 18 | 1.8 19 | 20 | 21 | 22 | 23 | com.alibaba 24 | druid-spring-boot-starter 25 | 1.1.10 26 | 27 | 28 | org.mybatis.spring.boot 29 | mybatis-spring-boot-starter 30 | 1.3.2 31 | 32 | 33 | tk.mybatis 34 | mapper-spring-boot-starter 35 | 2.1.5 36 | 37 | 38 | mysql 39 | mysql-connector-java 40 | 8.0.16 41 | 42 | 43 | 44 | org.springframework.boot 45 | spring-boot-starter-jdbc 46 | provided 47 | 48 | 49 | org.springframework.boot 50 | spring-boot-starter-aop 51 | provided 52 | 53 | 54 | 55 | org.springframework.boot 56 | spring-boot-starter-web 57 | 58 | 59 | 60 | org.springframework.boot 61 | spring-boot-starter-freemarker 62 | 63 | 64 | org.projectlombok 65 | lombok 66 | true 67 | 68 | 69 | com.alibaba 70 | fastjson 71 | 1.2.4 72 | 73 | 74 | org.springframework.boot 75 | spring-boot-starter-test 76 | test 77 | 78 | 79 | org.springframework.boot 80 | spring-boot-starter-data-jpa 81 | 82 | 83 | 84 | 85 | 86 | 87 | org.springframework.boot 88 | spring-boot-maven-plugin 89 | 90 | 91 | 92 | 93 | 94 | -------------------------------------------------------------------------------- /src/main/java/com/xjt/proxy/MysqlProxyApplication.java: -------------------------------------------------------------------------------- 1 | package com.xjt.proxy; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class MysqlProxyApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(MysqlProxyApplication.class, args); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/xjt/proxy/aop/DataSourceConfig.java: -------------------------------------------------------------------------------- 1 | package com.xjt.proxy.aop; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | import javax.sql.DataSource; 7 | 8 | import org.apache.ibatis.session.SqlSessionFactory; 9 | import org.mybatis.spring.SqlSessionFactoryBean; 10 | import org.mybatis.spring.SqlSessionTemplate; 11 | import org.springframework.beans.factory.annotation.Autowired; 12 | import org.springframework.beans.factory.annotation.Qualifier; 13 | import org.springframework.boot.context.properties.ConfigurationProperties; 14 | import org.springframework.context.annotation.Bean; 15 | import org.springframework.context.annotation.Configuration; 16 | import org.springframework.core.io.support.PathMatchingResourcePatternResolver; 17 | import org.springframework.jdbc.datasource.DataSourceTransactionManager; 18 | 19 | import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder; 20 | import com.xjt.proxy.dynamicdatasource.DynamicDataSource; 21 | import com.xjt.proxy.dynamicdatasource.DynamicDataSourceEnum; 22 | 23 | import tk.mybatis.spring.annotation.MapperScan; 24 | 25 | /** 26 | * 主从配置 27 | * 28 | * @author kevin 29 | * @date 2019-11-20 9:49 30 | */ 31 | @Configuration 32 | @MapperScan(basePackages = "com.xjt.proxy.mapper", sqlSessionTemplateRef = "sqlTemplate") 33 | public class DataSourceConfig { 34 | /** 35 | * 主库 36 | */ 37 | @Bean 38 | @ConfigurationProperties(prefix = "spring.datasource.master") 39 | public DataSource masterDb() { 40 | return DruidDataSourceBuilder.create().build(); 41 | } 42 | 43 | /** 44 | * 从库 45 | */ 46 | @Bean 47 | @ConfigurationProperties(prefix = "spring.datasource.slave") 48 | public DataSource slaveDb() { 49 | return DruidDataSourceBuilder.create().build(); 50 | } 51 | 52 | /** 53 | * 主从动态配置 54 | */ 55 | @Bean 56 | public DynamicDataSource dynamicDb(@Qualifier("masterDb") DataSource masterDataSource, 57 | @Autowired(required = false) @Qualifier("slaveDb") DataSource slaveDataSource) { 58 | DynamicDataSource dynamicDataSource = new DynamicDataSource(); 59 | Map targetDataSources = new HashMap<>(); 60 | targetDataSources.put(DynamicDataSourceEnum.MASTER.getDataSourceName(), masterDataSource); 61 | if (slaveDataSource != null) { 62 | targetDataSources.put(DynamicDataSourceEnum.SLAVE.getDataSourceName(), slaveDataSource); 63 | } 64 | dynamicDataSource.setTargetDataSources(targetDataSources); 65 | dynamicDataSource.setDefaultTargetDataSource(masterDataSource); 66 | return dynamicDataSource; 67 | } 68 | 69 | @Bean 70 | public SqlSessionFactory sessionFactory(@Qualifier("dynamicDb") DataSource dynamicDataSource) throws Exception { 71 | SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); 72 | bean.setMapperLocations( 73 | new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/*Mapper.xml")); 74 | bean.setDataSource(dynamicDataSource); 75 | return bean.getObject(); 76 | } 77 | 78 | @Bean 79 | public SqlSessionTemplate sqlTemplate(@Qualifier("sessionFactory") SqlSessionFactory sqlSessionFactory) { 80 | return new SqlSessionTemplate(sqlSessionFactory); 81 | } 82 | 83 | @Bean(name = "dataSourceTx") 84 | public DataSourceTransactionManager dataSourceTx(@Qualifier("dynamicDb") DataSource dynamicDataSource) { 85 | DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager(); 86 | dataSourceTransactionManager.setDataSource(dynamicDataSource); 87 | return dataSourceTransactionManager; 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /src/main/java/com/xjt/proxy/common/MyMapper.java: -------------------------------------------------------------------------------- 1 | package com.xjt.proxy.common; 2 | 3 | import tk.mybatis.mapper.common.Mapper; 4 | import tk.mybatis.mapper.common.MySqlMapper; 5 | 6 | /** 7 | * @author kevin 8 | * @date 2019-11-20 10:12 9 | */ 10 | public interface MyMapper extends Mapper, MySqlMapper { 11 | // TODO 12 | // FIXME 特别注意,该接口不能被扫描到,否则会出错 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/xjt/proxy/controller/UserController.java: -------------------------------------------------------------------------------- 1 | package com.xjt.proxy.controller; 2 | 3 | import java.util.List; 4 | 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.web.bind.annotation.RequestMapping; 7 | import org.springframework.web.bind.annotation.RestController; 8 | 9 | import com.xjt.proxy.domain.User; 10 | import com.xjt.proxy.service.UserService; 11 | 12 | /** 13 | * @author kevin 14 | * @date 2019-11-20 14:23 15 | */ 16 | @RestController 17 | @RequestMapping("/user") 18 | public class UserController { 19 | 20 | @Autowired 21 | private UserService userService; 22 | 23 | // @RequestMapping("/update") 24 | // public int update() { 25 | // return userService.update(); 26 | // } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/com/xjt/proxy/domain/User.java: -------------------------------------------------------------------------------- 1 | package com.xjt.proxy.domain; 2 | 3 | import java.util.Date; 4 | 5 | import javax.persistence.Column; 6 | import javax.persistence.Entity; 7 | import javax.persistence.Id; 8 | import javax.persistence.Table; 9 | 10 | import lombok.Data; 11 | 12 | /** 13 | * @author kevin 14 | * @date 2019-11-19 20:24 15 | */ 16 | @Data 17 | @Entity 18 | @Table(name = "user") 19 | public class User { 20 | @Id 21 | @Column(name = "user_id") 22 | private Long userId; 23 | 24 | @Column(name = "user_name") 25 | private String userName; 26 | 27 | @Column(name = "user_phone") 28 | private String userPhone; 29 | 30 | @Column(name = "address") 31 | private String address; 32 | 33 | @Column(name = "weight") 34 | private Integer weight; 35 | 36 | @Column(name = "created_at") 37 | private Date createdAt; 38 | 39 | @Column(name = "updated_at") 40 | private Date updatedAt; 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/com/xjt/proxy/dynamicdatasource/DataSourceContextAop.java: -------------------------------------------------------------------------------- 1 | package com.xjt.proxy.dynamicdatasource; 2 | 3 | import java.lang.reflect.Method; 4 | 5 | import org.aspectj.lang.JoinPoint; 6 | import org.aspectj.lang.ProceedingJoinPoint; 7 | import org.aspectj.lang.annotation.Around; 8 | import org.aspectj.lang.annotation.Aspect; 9 | import org.aspectj.lang.reflect.MethodSignature; 10 | import org.springframework.core.annotation.Order; 11 | import org.springframework.stereotype.Component; 12 | 13 | import lombok.extern.slf4j.Slf4j; 14 | 15 | /** 16 | * @author luoping 17 | */ 18 | @Slf4j 19 | @Aspect 20 | @Order(value = 1) 21 | @Component 22 | public class DataSourceContextAop { 23 | 24 | @Around("@annotation(com.xjt.proxy.dynamicdatasource.DataSourceSelector)") 25 | public Object setDynamicDataSource(ProceedingJoinPoint pjp) throws Throwable { 26 | boolean clear = true; 27 | try { 28 | Method method = this.getMethod(pjp); 29 | DataSourceSelector dataSourceImport = method.getAnnotation(DataSourceSelector.class); 30 | clear = dataSourceImport.clear(); 31 | DataSourceContextHolder.set(dataSourceImport.value().getDataSourceName()); 32 | log.info("========数据源切换至:{}", dataSourceImport.value().getDataSourceName()); 33 | return pjp.proceed(); 34 | } finally { 35 | if (clear) { 36 | DataSourceContextHolder.clear(); 37 | } 38 | 39 | } 40 | } 41 | 42 | private Method getMethod(JoinPoint pjp) { 43 | MethodSignature signature = (MethodSignature)pjp.getSignature(); 44 | return signature.getMethod(); 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/com/xjt/proxy/dynamicdatasource/DataSourceContextHolder.java: -------------------------------------------------------------------------------- 1 | package com.xjt.proxy.dynamicdatasource; 2 | 3 | /** 4 | * 5 | * @author luoping 6 | */ 7 | public class DataSourceContextHolder { 8 | private static final ThreadLocal DYNAMIC_DATASOURCE_CONTEXT = new ThreadLocal<>(); 9 | 10 | public static void set(String datasourceType) { 11 | DYNAMIC_DATASOURCE_CONTEXT.set(datasourceType); 12 | } 13 | 14 | public static String get() { 15 | return DYNAMIC_DATASOURCE_CONTEXT.get(); 16 | } 17 | 18 | public static void clear() { 19 | DYNAMIC_DATASOURCE_CONTEXT.remove(); 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/xjt/proxy/dynamicdatasource/DataSourceSelector.java: -------------------------------------------------------------------------------- 1 | package com.xjt.proxy.dynamicdatasource; 2 | 3 | import java.lang.annotation.*; 4 | 5 | /** 6 | * @author luoping 7 | */ 8 | @Retention(RetentionPolicy.RUNTIME) 9 | @Target(ElementType.METHOD) 10 | @Documented 11 | public @interface DataSourceSelector { 12 | 13 | DynamicDataSourceEnum value() default DynamicDataSourceEnum.MASTER; 14 | 15 | boolean clear() default true; 16 | 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/com/xjt/proxy/dynamicdatasource/DynamicDataSource.java: -------------------------------------------------------------------------------- 1 | package com.xjt.proxy.dynamicdatasource; 2 | 3 | import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource; 4 | 5 | /** 6 | * @author luoping 7 | */ 8 | 9 | public class DynamicDataSource extends AbstractRoutingDataSource { 10 | 11 | @Override 12 | protected Object determineCurrentLookupKey() { 13 | return DataSourceContextHolder.get(); 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/xjt/proxy/dynamicdatasource/DynamicDataSourceEnum.java: -------------------------------------------------------------------------------- 1 | package com.xjt.proxy.dynamicdatasource; 2 | 3 | import lombok.Getter; 4 | 5 | /** 6 | * @author luoping 7 | */ 8 | @Getter 9 | public enum DynamicDataSourceEnum { 10 | /** 11 | * 主库 12 | */ 13 | MASTER("master"), 14 | /** 15 | * 从库 16 | */ 17 | SLAVE("slave"); 18 | 19 | private String dataSourceName; 20 | 21 | DynamicDataSourceEnum(String dataSourceName) { 22 | this.dataSourceName = dataSourceName; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/com/xjt/proxy/mapper/UserMapper.java: -------------------------------------------------------------------------------- 1 | package com.xjt.proxy.mapper; 2 | 3 | import com.xjt.proxy.common.MyMapper; 4 | import com.xjt.proxy.domain.User; 5 | 6 | /** 7 | * @author kevin 8 | * @date 2019-11-20 10:05 9 | */ 10 | public interface UserMapper extends MyMapper {} 11 | -------------------------------------------------------------------------------- /src/main/java/com/xjt/proxy/service/UserService.java: -------------------------------------------------------------------------------- 1 | package com.xjt.proxy.service; 2 | 3 | import java.util.Date; 4 | import java.util.List; 5 | 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.stereotype.Service; 8 | 9 | import com.xjt.proxy.domain.User; 10 | import com.xjt.proxy.dynamicdatasource.DataSourceSelector; 11 | import com.xjt.proxy.dynamicdatasource.DynamicDataSourceEnum; 12 | import com.xjt.proxy.mapper.UserMapper; 13 | import org.springframework.transaction.annotation.Transactional; 14 | import org.springframework.validation.annotation.Validated; 15 | 16 | /** 17 | * @author kevin 18 | * @date 2019-11-20 10:16 19 | */ 20 | @Service 21 | public class UserService { 22 | 23 | @Autowired 24 | private UserMapper userMapper; 25 | 26 | @DataSourceSelector(value = DynamicDataSourceEnum.MASTER) 27 | public int update(Long userId) { 28 | User user = new User(); 29 | user.setUserId(userId); 30 | user.setUserName("老薛"); 31 | return userMapper.updateByPrimaryKeySelective(user); 32 | } 33 | 34 | @DataSourceSelector(value = DynamicDataSourceEnum.SLAVE) 35 | public User find(Long userId) { 36 | User user = new User(); 37 | user.setUserId(userId); 38 | return userMapper.selectByPrimaryKey(user); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | server: 2 | port: 8001 3 | spring: 4 | jackson: 5 | date-format: yyyy-MM-dd HH:mm:ss 6 | time-zone: GMT+8 7 | datasource: 8 | type: com.alibaba.druid.pool.DruidDataSource 9 | driver-class-name: com.mysql.cj.jdbc.Driver 10 | master: 11 | url: jdbc:mysql://127.0.0.1:3307/test?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&failOverReadOnly=false&useSSL=false&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true 12 | username: root 13 | password: 123456 14 | slave: 15 | url: jdbc:mysql://127.0.0.1:3308/test?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&failOverReadOnly=false&useSSL=false&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true 16 | username: root 17 | password: 123456 18 | freemarker: 19 | template-loader-path: classpath:/templates 20 | cache: false 21 | charset: UTF-8 22 | check-template-location: true 23 | content-type: text/html 24 | expose-request-attributes: true 25 | expose-session-attributes: true 26 | request-context-attribute: request 27 | suffix: .ftl 28 | redis: 29 | host: 127.0.0.1 30 | port: 6379 31 | password: 32 | database: 11 33 | # pool: 34 | # max-active: 100 35 | # max-wait: -1 36 | # max-idle: 20 37 | # min-idle: 10 38 | lettuce: 39 | pool: 40 | # 最大连接数 41 | max-active: 20 42 | # 最大能够保持idel状态的连接数 43 | max-idle: 20 44 | # 最小能够保持idel状态的连接数 45 | min-idle: 10 46 | # 当池内没有返回对象时,最大等待时间 47 | max-wait: 5000ms -------------------------------------------------------------------------------- /src/main/resources/logback-spring.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 7 | 9 | 10 | 11 | 12 | 13 | ${STDOUT_PATTERN} 14 | 15 | 16 | 17 | 18 | 19 | ${logPath}/info.log 20 | 21 | INFO 22 | 23 | 24 | 25 | ${LOG_PATTERN} 26 | 27 | UTF-8 28 | 29 | 30 | 31 | ${logPath}/info.%d{yyyy-MM-dd}.log 32 | 33 | 90 34 | 35 | 36 | 37 | 38 | 39 | ${logPath}/error.log 40 | 41 | ERROR 42 | 43 | 44 | 45 | ${LOG_PATTERN} 46 | 47 | 48 | 49 | 50 | 51 | ${logPath}/error.%d{yyyy-MM-dd}.log 52 | 53 | 90 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | -------------------------------------------------------------------------------- /src/main/resources/mapper/UserMapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /src/main/resources/sql/user.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Navicat MySQL Data Transfer 3 | 4 | Source Server : mysql2 5 | Source Server Version : 50727 6 | Source Host : localhost:3308 7 | Source Database : user 8 | 9 | Target Server Type : MYSQL 10 | Target Server Version : 50727 11 | File Encoding : 65001 12 | 13 | Date: 2019-11-19 20:33:26 14 | */ 15 | 16 | SET FOREIGN_KEY_CHECKS=0; 17 | 18 | -- ---------------------------- 19 | -- Table structure for user 20 | -- ---------------------------- 21 | DROP TABLE IF EXISTS `user`; 22 | CREATE TABLE `user` ( 23 | `user_id` bigint(20) NOT NULL COMMENT '用户id', 24 | `user_name` varchar(255) DEFAULT '' COMMENT '用户名称', 25 | `user_phone` varchar(50) DEFAULT '' COMMENT '用户手机', 26 | `address` varchar(255) DEFAULT '' COMMENT '住址', 27 | `weight` int(3) NOT NULL DEFAULT '1' COMMENT '权重,大者优先', 28 | `created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', 29 | `updated_at` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', 30 | PRIMARY KEY (`user_id`) 31 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8; 32 | 33 | -- ---------------------------- 34 | -- Records of user 35 | -- ---------------------------- 36 | -------------------------------------------------------------------------------- /src/test/java/com/xjt/proxy/MysqlProxyApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.xjt.proxy; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.boot.test.context.SpringBootTest; 5 | 6 | @SpringBootTest 7 | class MysqlProxyApplicationTests { 8 | 9 | @Test 10 | void contextLoads() {} 11 | 12 | } 13 | -------------------------------------------------------------------------------- /src/test/java/com/xjt/proxy/service/UserServiceTest.java: -------------------------------------------------------------------------------- 1 | package com.xjt.proxy.service; 2 | 3 | import java.util.List; 4 | 5 | import org.junit.jupiter.api.Test; 6 | import org.junit.runner.RunWith; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.boot.test.context.SpringBootTest; 9 | import org.springframework.test.context.junit4.SpringRunner; 10 | 11 | import com.xjt.proxy.domain.User; 12 | 13 | /** 14 | * @author kevin 15 | * @date 2019-11-22 16:02 16 | */ 17 | @RunWith(SpringRunner.class) 18 | @SpringBootTest 19 | class UserServiceTest { 20 | 21 | @Autowired 22 | UserService userService; 23 | 24 | @Test 25 | void find() { 26 | User user = userService.find(1196978513958141952L); 27 | System.out.println("id:" + user.getUserId()); 28 | System.out.println("name:" + user.getUserName()); 29 | System.out.println("phone:" + user.getUserPhone()); 30 | } 31 | 32 | @Test 33 | void update() { 34 | Long userId = 1196978513958141952L; 35 | userService.update(userId); 36 | User user = userService.find(userId); 37 | System.out.println(user.getUserName()); 38 | } 39 | 40 | } --------------------------------------------------------------------------------