当前位置: 首页 > news >正文

在Spring boot 中使用@master 设置主从数据库

基础配置

application.yml

spring:
  datasource:
    master:
      url: jdbc:mysql://localhost:3306/master_db
      username: root
      password: 123456
      driver-class-name: com.mysql.cj.jdbc.Driver
    slave:
      url: jdbc:mysql://localhost:3306/slave_db
      username: root
      password: 123456
      driver-class-name: com.mysql.cj.jdbc.Driver
mybatis:
  mapper-locations: classpath:mapper/*.xml

DataSourceConfig

package com.example.multids.config;import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;@Configuration
public class DataSourceConfig {// 主数据源配置(前缀对应application.yml中的spring.datasource.master)
    @Bean@ConfigurationProperties(prefix = "spring.datasource.master")public DataSource masterDataSource() {return DataSourceBuilder.create().build();}// 从数据源配置
    @Bean@ConfigurationProperties(prefix = "spring.datasource.slave")public DataSource slaveDataSource() {return DataSourceBuilder.create().build();}// 动态数据源路由
    @Beanpublic DataSource routingDataSource(DataSource masterDataSource, DataSource slaveDataSource) {AbstractRoutingDataSource routingDataSource = new AbstractRoutingDataSource() {@Overrideprotected Object determineCurrentLookupKey() {return DataSourceContextHolder.getDataSourceType();}};Map<Object, Object> targetDataSources = new HashMap<>();targetDataSources.put("master", masterDataSource);targetDataSources.put("slave", slaveDataSource);routingDataSource.setDefaultTargetDataSource(masterDataSource);routingDataSource.setTargetDataSources(targetDataSources);return routingDataSource;}
}

DataSourceContextHolder

package com.example.multids.config;public class DataSourceContextHolder {private static final ThreadLocal<String> contextHolder = new ThreadLocal<>();// 设置当前线程数据源类型public static void setDataSourceType(String dsType) {contextHolder.set(dsType);}// 获取当前线程数据源类型public static String getDataSourceType() {return contextHolder.get();}// 清除数据源类型public static void clearDataSourceType() {contextHolder.remove();}
}

Master

package com.example.multids.annotation;import java.lang.annotation.*;@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Master {// 标记使用主数据源
}

DataSourceAspect

package com.example.multids.aspect;import com.example.multids.annotation.Master;
import com.example.multids.config.DataSourceContextHolder;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;@Aspect
@Component
@Order(-1) // 保证在事务注解前执行
public class DataSourceAspect {@Around("@annotation(master)")public Object around(ProceedingJoinPoint point, Master master) throws Throwable {try {DataSourceContextHolder.setDataSourceType("master");return point.proceed();} finally {DataSourceContextHolder.clearDataSourceType();}}
}

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></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>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency></dependencies>
</project>

 

http://www.rkmt.cn/news/2689.html

相关文章:

  • 第 16 章反射(reflection)
  • 设计模式-组合模式 - MaC
  • 【推荐】100%开源!大型工业跨平台软件C++源码提供,建模,组态
  • 设计模式-桥接模式 - MaC
  • Python 降序排序:轻松搞定列表、字典和自定义对象
  • 第02周 预习、实验与作业:Java基础语法2、面向对象入门
  • 2025实测:6款主流公众号编辑器大比拼,解决你的排版难题!
  • 设计模式-适配器模式 - MaC
  • 达梦数据库安装和使用
  • Ubuntu 界面变为 Mac
  • PVE9环境下飞牛OS安装vGPU驱动
  • 02020304 .NET Core核心基础组件04-配置系统、Json文件配置、选项方式读取、扁平化环境变量其它配置源
  • md格式
  • 第7篇、Kafka Streams 与 Connect:企业级实时数据处理架构实践指南
  • 202207_BUGKU_二维码GIF
  • 20250910NOIP模拟赛
  • 【2025最新推荐】AI大模型API中转站 | 国内直连ChatGPT/Claude/Gemini全系API接口服务
  • html怎么写
  • 无重复字符的最长子串-leetcode
  • 两个常见的 计数问题 trick
  • 202110_绿盟杯_隐藏的数据
  • 线上课
  • 弹窗、抽屉、当前页和新开页,到底怎么选? - 智慧园区
  • 搜维尔科技:Haption触觉力反馈系统,沉浸式远程呈现、数字孪生、混合现实和移动远程机器人
  • 飞书免费企业邮箱推荐
  • sites(legal - Gon
  • 解决推理能力瓶颈,用因果推理提升LLM智能决策
  • 123
  • GitHub Copilot 代码评审:用于自动评审的独立存储库规则
  • 张量链式法则(上篇):任意维度反向传播公式推导与常见算子解析