一、创建SpringBoot项目并添加依赖,完整pom如下:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>cn.edu.tju</groupId>
<artifactId>springbootmysqlmasterslave</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.7.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>3.4.14</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.6</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.30</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-openfeign -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
<version>2.1.5.RELEASE</version>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.13</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>3.0.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
二、在application.properties中配置主数据源和从数据源:
server.port=9093
spring.datasource.master.jdbc-url=jdbc:mysql://139.xxx.xxx.xxx:3306/test?useUnicode=true&characterEncoding=utf8&tinyInt1isBit=false&useSSL=false&serverTimezone=GMT
spring.datasource.master.username=root
spring.datasource.master.password=xxx
spring.datasource.master.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.slave1.jdbc-url=jdbc:mysql://139.xxx.xxx.xxx:3306/test?useUnicode=true&characterEncoding=utf8&tinyInt1isBit=false&useSSL=false&serverTimezone=GMT
spring.datasource.slave1.username=root
spring.datasource.slave1.password=xxx
spring.datasource.slave1.driver-class-name=com.mysql.jdbc.Driver
三、创建枚举,分别表示主数据源和从数据源
package cn.edu.tju.config;
public enum DataSourceEnum {
MASTER, SLAVE1
}
四、创建Holder静态类,持有上述枚举,并提供修改功能
package cn.edu.tju.config;
public class DataSourceContextHolder {
private static final ThreadLocal<DataSourceEnum> contextHolder = new ThreadLocal<>();
public static void setDataSource(DataSourceEnum dataSourceEnum) {
contextHolder.set(dataSourceEnum);
}
public static DataSourceEnum get() {
return contextHolder.get();
}
public static void switchToMasterDatabase() {
setDataSource(DataSourceEnum.MASTER);
System.out.println("switch to master");
}
public static void switchToSlaveDatabase() {
setDataSource(DataSourceEnum.values()[1]);
System.out.println("switch to "+DataSourceEnum.values()[1]);
}
public static void remove(){
contextHolder.remove();
}
}
五、定义AbstractRoutingDataSource的子类,通过上述Holder类,来实现数据源的切换
package cn.edu.tju.config;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
public class MyRoutingDataSource extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
return DataSourceContextHolder.get();
}
}
六、定义主数据源bean、从数据源bean、RoutingDataSource bean;
package cn.edu.tju.config;
import java.util.Map;
import java.util.HashMap;
import javax.sql.DataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
@Configuration
public class DataSourceConfig {
@Bean
@ConfigurationProperties("spring.datasource.master")
public DataSource masterDataSource() {
return DataSourceBuilder.create().build();
}
@Bean
@ConfigurationProperties("spring.datasource.slave1")
public DataSource slave1DataSource() {
return DataSourceBuilder.create().build();
}
@Bean("targetDataSources")
public DataSource getRoutingDataSource(@Qualifier("masterDataSource") DataSource masterDataSource,
@Qualifier("slave1DataSource") DataSource slave1DataSource) {
Map<Object, Object> targetDataSources = new HashMap<>();
targetDataSources.put(DataSourceEnum.MASTER, masterDataSource);
targetDataSources.put(DataSourceEnum.SLAVE1, slave1DataSource);
MyRoutingDataSource myRoutingDataSource = new MyRoutingDataSource();
myRoutingDataSource.setDefaultTargetDataSource(masterDataSource);
myRoutingDataSource.setTargetDataSources(targetDataSources);
return myRoutingDataSource;
}
}
7、定义SqlSessionFactory
package cn.edu.tju.config;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.annotation.Resource;
import javax.sql.DataSource;
@Configuration
@MapperScan(basePackages = "cn.edu.tju.mapper", sqlSessionFactoryRef = "sqlSessionFactory")
@EnableTransactionManagement
public class SqlSessionFactoryConfig {
@Resource(name = "targetDataSources")
private DataSource dataSource;
@Bean
public SqlSessionFactory sqlSessionFactory() throws Exception {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource);
sqlSessionFactoryBean.getObject().getConfiguration().setMapUnderscoreToCamelCase(true);
return sqlSessionFactoryBean.getObject();
}
@Bean
public PlatformTransactionManager platformTransactionManager(){
return new DataSourceTransactionManager(dataSource);
}
}
八、定义一个用来强制路由到主数据源的注解
package cn.edu.tju.aop;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface SelectMasterDatabase {
}
九、定义Aspect,用来对控制器的请求进行增强处理,读请求路由到从数据源,写请求路由到主数据源
package cn.edu.tju.aop;
import cn.edu.tju.config.DataSourceContextHolder;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class DataSourceSelectAop {
@Pointcut("!@annotation(cn.edu.tju.aop.SelectMasterDatabase) && (execution(* cn.edu.tju.service.*.get*(..)))")
public void readPointcut() {
}
@Pointcut("@annotation(cn.edu.tju.aop.SelectMasterDatabase) " +
"|| execution(* cn.edu.tju.service.*.add*(..)) " +
"|| execution(* cn.edu.tju.service.*.delete*(..)) " +
"|| execution(* cn.edu.tju.service.*.update*(..)) " )
public void writePointcut() {
}
@Before("readPointcut()")
public void read() {
DataSourceContextHolder.switchToSlaveDatabase();
}
@Before("writePointcut()")
public void write() {
DataSourceContextHolder.switchToMasterDatabase();
}
}
十、准备启动类\mapper\service\controller,启动程序
package cn.edu.tju;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Start {
public static void main(String[] args) {
SpringApplication.run(Start.class,args);
}
}
package cn.edu.tju.mapper;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import java.util.Map;
public interface UserMapper {
@Select("select * from user_info where username like 'cho%' limit 1")
Map<String,Object> getUserInfo();
@Insert("insert into user_info(username,passwd) values(#{arg0},#{arg1})")
int addUserInfo(String username,String password);
}
package cn.edu.tju.service;
import cn.edu.tju.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Map;
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public Map<String,Object> getUser(){
Map<String,Object> map=userMapper.getUserInfo();
return map;
}
public int addUserInfo(String username,String password){
return userMapper.addUserInfo(username,password);
}
}
package cn.edu.tju.controller;
import cn.edu.tju.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
@RestController
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/get")
public Map<String,Object> getUser(){
return userService.getUser();
}
@RequestMapping("/add")
public int addUser(){
return userService.addUserInfo("Ludwig","Beethoven1770");
}
}
十一、调用add接口和get接口并在数据库查看结果: 写入数据会写到主数据源,然后被自动同步到从数据源 读取数据会从从数据源读。 这样就完成了读写分离。
|