1. 程式人生 > 資料庫 >springboot+mysql讀寫分離

springboot+mysql讀寫分離

在javaweb開發中資料庫表資料量會越來越大,為了減輕資料庫讀寫壓力,對資料庫進行主從模式部署(一主一從,多主多從),在應用層面可以通過spring提供的路由資料來源+註解+切面進行控制,在程式碼層面切換不同資料庫源,不同操作選擇不同資料庫。

程式碼如下:

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.9</version>
        </dependency>
        <!-- 引入mybatis 依賴-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.1.1</version>
        </dependency>
        <!-- mysql 依賴-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <!--<scope>runtime</scope>-->
        </dependency>
spring.datasource.master.url=jdbc:mysql://localhost:3306/master?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=false
spring.datasource.master.username=root
spring.datasource.master.password=123456
spring.datasource.master.driver-class-name=com.mysql.cj.jdbc.Driver

spring.datasource.slave.url=jdbc:mysql://localhost:3306/slave?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=false
spring.datasource.slave.username=root
spring.datasource.slave.password=123456
spring.datasource.slave.driver-class-name=com.mysql.cj.jdbc.Driver
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class, TransactionAutoConfiguration.class})
@MapperScan("com.*.mapper")
public class AnnotationAopReflectionApplication {
    public static void main(String[] args) {
        SpringApplication.run(AnnotationAopReflectionApplication.class, args);
    }
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Documented
public @interface DataSourceAnnotation {
    /**
     * 預設資料來源
     */
    DataSourceEnum value() default DataSourceEnum.MASTER;
    /**
     * 清除
     */
    boolean clear() default true;
}
public enum DataSourceEnum {

    //資料來源主庫、從庫
    MASTER("1","master"),
    SLAVE("2","slave");

    private String code;
    private String name;

    private DataSourceEnum(String code,String name){
        this.code = code;
        this.name = name;
    }

    public static DataSourceEnum getByCode(String code) {
        for (DataSourceEnum event : DataSourceEnum.values()) {
            if (event.code.equals(code)) {
                return event;
            }
        }
        return null;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}
public class DataSourceContextHolder {

    private static final ThreadLocal<String> context = new ThreadLocal<>();

    /**
     * 賦值
     */
    public static void set(String datasourceType) {
        context.set(datasourceType);
    }

    /**
     * 獲取值
     */
    public static String get() {
        return context.get();
    }

    /**
     * 清空
     */
    public static void clear() {
        context.remove();
    }

}
public class RoutingDataSource extends AbstractRoutingDataSource {

    /**
     * 最終的determineCurrentLookupKey返回的是從DataSourceContextHolder中拿到的,因此在動態切換資料來源的時候註解
     * 應該給DataSourceContextHolder設值
     */
    @Override
    protected Object determineCurrentLookupKey() {
        return DataSourceContextHolder.get();
    }

}
@Configuration
@MapperScan(basePackages = "com.", sqlSessionTemplateRef = "sqlSessionTemplate")
public class DataSourceConfig {

    /**
     * 主庫
     */
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.master")
    public DataSource master() {
        return DruidDataSourceBuilder.create().build();
    }

    /**
     * 從庫
     */
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.slave")
    public DataSource slaver() {
        return DruidDataSourceBuilder.create().build();
    }

    /**
     * 例項化資料來源路由
     */
    @Bean
    public RoutingDataSource routingDataSource(@Qualifier("master") DataSource masterDataSource,@Autowired(required = false) @Qualifier("slaver") DataSource slaveDataSource) {
        RoutingDataSource routingDataSource = new RoutingDataSource();
        Map<Object, Object> targetDataSources = new HashMap<>();
        targetDataSources.put(DataSourceEnum.MASTER.getName(), masterDataSource);
        if (slaveDataSource != null) {
            targetDataSources.put(DataSourceEnum.SLAVE.getName(), slaveDataSource);
        }
        routingDataSource.setTargetDataSources(targetDataSources);
        routingDataSource.setDefaultTargetDataSource(masterDataSource);
        return routingDataSource;
    }

    /**
     * 配置sessionFactory
     */
    @Bean
    public SqlSessionFactory sqlSessionFactory(@Qualifier("routingDataSource") DataSource routingDataSource) throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/*.xml"));
        sqlSessionFactoryBean.setDataSource(routingDataSource);
        return sqlSessionFactoryBean.getObject();
    }

    /**
     * 建立sqlSessionTemplate
     */
    @Bean
    public SqlSessionTemplate sqlSessionTemplate(@Qualifier("sqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    /**
     * 事務配置
     */
    @Bean(name = "dataSourceTransactionManager")
    public DataSourceTransactionManager dataSourceTransactionManager(@Qualifier("routingDataSource") DataSource dynamicDataSource) {
        DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
        dataSourceTransactionManager.setDataSource(dynamicDataSource);
        return dataSourceTransactionManager;
    }

}
@Aspect
@Order(value = 1)
@Component
public class DataSourceAspect {

    @Around("@annotation(com.*.DataSourceAnnotation)")
    public Object setDynamicDataSource(ProceedingJoinPoint pjp) throws Throwable {
        boolean clear = false;
        try {
            Method method = this.getMethod(pjp);
            DataSourceAnnotation dataSourceAnnotation = method.getAnnotation(DataSourceAnnotation.class);
            clear = dataSourceAnnotation.clear();
            DataSourceContextHolder.set(dataSourceAnnotation.value().getName());
            System.out.println(String.format("資料來源切換至:{%s}", dataSourceAnnotation.value().getName()));
            return pjp.proceed();
        } finally {
            if (clear) {
                DataSourceContextHolder.clear();
            }
        }
    }

    private Method getMethod(JoinPoint pjp) {
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        return signature.getMethod();
    }

}
@Service
public class DemoService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AuthUserMapper authUserMapper;

    /**
     * 讀操作
     */
    @DataSourceAnnotation(DataSourceEnum.SLAVE)
    public AuthUser getAuthUser() {
        String userId = "001";
        AuthUser authUser = authUserMapper.getAuthUserById(userId);
        //User user = userMapper.getUserById(1);
        return authUser;
    }

    /**
     * 寫操作
     */
    @DataSourceAnnotation(DataSourceEnum.MASTER)
    public User updateUser() {
        User user = userMapper.getUserById(1);
        return user;
    }

}
@RestController
public class DemoController {
    
    @Autowired
    private DemoService demoService;

    @GetMapping("/readSlave")
    public Object readSlave() {
        return demoService.getAuthUser();
    }

    @GetMapping("/writeMaster")
    public Object writeMaster() {
        return demoService.updateUser();
    }

}

前提是部署好mysql主從資料庫或準備不同資料庫。注意讀寫分離的核心點就是資料路由,需要繼承AbstractRountingDataSource,覆寫它的determinCurrentLookupKey方法,同時需要注意全域性的上下文管理器DataSourceContextHolder,它是儲存資料來源上下文的主要類,也是路由方法中尋找的資料來源取值,相當於資料來源的中轉站,此例配置了3個數據源。再結合jdbc底層、事務等,資料庫讀寫分離就實現了。