单体应用-SpringBoot-(2)动态数据源

本文详细介绍SpringBoot环境下多数据源的配置与动态切换实践,包括Druid连接池的使用,JPA集成,以及自定义数据源上下文和注解切面的实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

主要参考抄袭自SpringBoot之多数据源动态切换数据源
顺道看了看抄了抄:
springboot+jpa多数据源配置实例
SpringBoot重点详解–使用Druid+Jpa
自定义配置JPA使用多数据源

简单配置

分模块后,接着做一下应用的简单配置:

  • 数据源
  • redis连接池
  • jpa

SpringBoot同时支持 .properties 和.yml 的配置文件。
我这同时使用了,因为拷贝别人的配置比较方便。
路径在Web模块的 src/man/resources下。默认会生成application.properties 的文件,我们再创建个application.yml。

application.yml
设置了主数据源和两个业务数据源(可以是多个)
主数据源用来存放用户,角色,权限,组织架构等数据。
业务数据源存放不同业务数据,如订单等等。多个业务数据源类似于集团下各公司的业务数据。
DataSource使用druid连接池。

spring:
  datasource:
    master:
      url: jdbc:mysql://localhost:3306/dj?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8&useSSL=false
      driver-class-name: com.mysql.cj.jdbc.Driver
      username: root
      password: xxxx
      type: com.alibaba.druid.pool.DruidDataSource
    cluster:
      - key: slave1
        url: jdbc:mysql://localhost:3306/m2?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8&useSSL=false
        driver-class-name: com.mysql.cj.jdbc.Driver
        username: root
        password: xxxx
        type: com.alibaba.druid.pool.DruidDataSource
      - key: slave2
        url: jdbc:mysql://localhost:3306/m3?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8&useSSL=false
        driver-class-name: com.mysql.cj.jdbc.Driver
        username: root
        password: xxxx
        type: com.alibaba.druid.pool.DruidDataSource

application.properties
application.version之后会用到。
这里JPA的配置,每次服务启动都会去检查@Table的实体类在数据库里面有没有存在表,更新表结构。(测试了下,只有默认数据源都会创建和更新,其他数据源的表如何自动创建有待研究)

application.version=1.0

# redis
spring.redis.database=0
spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.password=
spring.redis.jedis.pool.max-active=8
spring.redis.jedis.pool.max-idle=8
spring.redis.jedis.pool.max-wait=-1ms
spring.redis.jedis.pool.min-idle=0
spring.redis.timeout=10000ms

# JPA
spring.jpa.database=MYSQL
#spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect
# 配置是否将执行的 SQL 输出到日志
spring.jpa.show-sql=true
# create:每次运行程序时,都会重新创建表,故而数据会丢失
# create-drop:每次运行程序时会先创建表结构,然后待程序结束时清空表
# upadte:每次运行程序,没有表时会创建表,如果对象发生改变会更新表结构,原有数据不会清空,只会更新(推荐使用)
# validate:运行程序会校验数据与数据库的字段类型是否相同,字段不同会报错
# none: 禁用DDL处理
spring.jpa.hibernate.ddl-auto=update

其他很多配置事情SpringBoot帮我们做了,运行时候也会帮我们生成各自的Bean对象。我们可以在配置文件增加一些属性来修改配置,也可以写一些配置类覆盖SpringBoot的自动配置。没做深究,用到再找。

我觉得比较好玩的是SpringBoot可以自定义Banner,服务启动时候的图案。

可以参考Spring Boot自定义Banner

配置文件的application.version就有在这里用到:
路径也在src/man/resources下,服务启动的时候画面就比较舒适。
在这里插入图片描述

使用动态数据源

这部分目前被我放在Core模块下,思路如下:

  1. 定义一个数据源上下文,使用ThreadLocal做线程隔离,存放每个线程使用的数据源key

  2. 注册绑定数据源,不使用springboot自动生成的datasource。

  3. 定义一个类继承AbstractRoutingDataSource, 通知spring当前的数据源key

  4. 辅助功能:定义注解,定义切面,可以在方法和类级别上使用注解,来切换数据源。

  5. 对所有请求进行拦截,根据token解析出用户名,获取该用户使用的数据源,变更数据源上下文中的数据源key,这个步骤因为和用户权限等整合在一起,下一篇再介绍,该实现目前被我丢在Web模块。

接下来贴一下每个步骤的实现:

数据源上下文:
public class DynamicDataSourceContextHolder {
    /**
     * 存储已经注册的数据源的key
     */
    public static List<String> dataSourceIds = new ArrayList<>();

    /**
     * 线程级别的私有变量
     */
    private static final ThreadLocal<String> HOLDER = new ThreadLocal<>();

    public static String getDataSourceRouterKey () {
        return HOLDER.get();
    }

    public static void setDataSourceRouterKey (String dataSourceRouterKey) {
        HOLDER.set(dataSourceRouterKey);
    }

    /**
     * 设置数据源之前一定要先移除
     */
    public static void removeDataSourceRouterKey () {
        HOLDER.remove();
    }

    /**
     * 判断指定DataSrouce当前是否存在
     */
    public static boolean containsDataSource(String dataSourceId){
        return dataSourceIds.contains(dataSourceId);
    }
    
}
注册绑定数据源:
public class DynamicDataSourceRegister implements ImportBeanDefinitionRegistrar, EnvironmentAware {

    private static final Logger logger = LoggerFactory.getLogger(DynamicDataSourceRegister.class);

    /**
     * 配置上下文(也可以理解为配置文件的获取工具)
     */
    private Environment evn;
    /**
     * 别名
     */
    private final static ConfigurationPropertyNameAliases ALIASES = new ConfigurationPropertyNameAliases();

    /**
     * 由于部分数据源配置不同,所以在此处添加别名,避免切换数据源出现某些参数无法注入的情况
     */
    static {
        ALIASES.addAliases("url", new String[]{"jdbc-url"});
        ALIASES.addAliases("username", new String[]{"user"});
    }
    /**
     * 存储我们注册的数据源
     */
    private Map<String, DataSource> customDataSources = new HashMap<String, DataSource>();

    /**
     * 参数绑定工具 springboot2.0新推出
     */
    private Binder binder;

    /**
     * ImportBeanDefinitionRegistrar接口的实现方法,通过该方法可以按照自己的方式注册bean
     */
    @Override
    public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry beanDefinitionRegistry) {
        // 获取所有数据源配置
        Map config, defaultDataSourceProperties;
        defaultDataSourceProperties = binder.bind("spring.datasource.master", Map.class).get();
        // 获取数据源类型
        String typeStr = evn.getProperty("spring.datasource.master.type");
        // 获取数据源类型
        Class<? extends DataSource> clazz = getDataSourceType(typeStr);
        // 绑定默认数据源参数 也就是主数据源
        DataSource consumerDatasource, defaultDatasource = bind(clazz, defaultDataSourceProperties);
        DynamicDataSourceContextHolder.dataSourceIds.add("master");
        logger.info("注册默认数据源成功");

        // 获取其他数据源配置
        List<Map> configs = binder.bind("spring.datasource.cluster", Bindable.listOf(Map.class)).get();
        // 遍历从数据源
        for (int i = 0; i < configs.size(); i++) {
            config = configs.get(i);
            clazz = getDataSourceType((String) config.get("type"));
            defaultDataSourceProperties = config;
            // 绑定参数
            consumerDatasource = bind(clazz, defaultDataSourceProperties);
            // 获取数据源的key,以便通过该key可以定位到数据源
            String key = config.get("key").toString();
            customDataSources.put(key, consumerDatasource);
            // 数据源上下文,用于管理数据源与记录已经注册的数据源key
            DynamicDataSourceContextHolder.dataSourceIds.add(key);
            logger.info("注册数据源{}成功", key);
        }

        // bean定义类
        GenericBeanDefinition define = new GenericBeanDefinition();
        // 设置bean的类型,此处DynamicRoutingDataSource是继承AbstractRoutingDataSource的实现类
        define.setBeanClass(DynamicRoutingDataSource.class);
        // 需要注入的参数
        MutablePropertyValues mpv = define.getPropertyValues();
        // 添加默认数据源,避免key不存在的情况没有数据源可用
        mpv.add("defaultTargetDataSource", defaultDatasource);
        // 添加其他数据源
        mpv.add("targetDataSources", customDataSources);
        // 将该bean注册为datasource,不使用springboot自动生成的datasource
        beanDefinitionRegistry.registerBeanDefinition("datasource", define);
        logger.info("注册数据源成功,一共注册{}个数据源", customDataSources.keySet().size() + 1);
    }

    /**
     * 通过字符串获取数据源class对象
     */
    private Class<? extends DataSource> getDataSourceType(String typeStr) {
        Class<? extends DataSource> type;
        try {
            if (StringUtils.hasLength(typeStr)) {
                // 字符串不为空则通过反射获取class对象
                type = (Class<? extends DataSource>) Class.forName(typeStr);
            } else {
                // 默认为hikariCP数据源,与springboot默认数据源保持一致
                type = HikariDataSource.class;
            }
            return type;
        } catch (Exception e) {
            //无法通过反射获取class对象的情况则抛出异常,该情况一般是写错了,所以此次抛出一个runtimeexception
            throw new IllegalArgumentException("生成类对象错误: " + typeStr);
        }
    }

    /**
     * 绑定参数,以下三个方法都是参考DataSourceBuilder的bind方法实现的,目的是尽量保证我们自己添加的数据源构造过程与springboot保持一致
     */
    private void bind(DataSource result, Map properties) {
        ConfigurationPropertySource source = new MapConfigurationPropertySource(properties);
        Binder binder = new Binder(new ConfigurationPropertySource[]{source.withAliases(ALIASES)});
        // 将参数绑定到对象
        binder.bind(ConfigurationPropertyName.EMPTY, Bindable.ofInstance(result));
    }

    private <T extends DataSource> T bind(Class<T> clazz, Map properties) {
        ConfigurationPropertySource source = new MapConfigurationPropertySource(properties);
        Binder binder = new Binder(new ConfigurationPropertySource[]{source.withAliases(ALIASES)});
        // 通过类型绑定参数并获得实例对象
        return binder.bind(ConfigurationPropertyName.EMPTY, Bindable.of(clazz)).get();
    }

    /**
     * @param clazz
     * @param sourcePath 参数路径,对应配置文件中的值,如: spring.datasource
     * @param <T>
     * @return
     */
    private <T extends DataSource> T bind(Class<T> clazz, String sourcePath) {
        Map properties = binder.bind(sourcePath, Map.class).get();
        return bind(clazz, properties);
    }

    /**
     * EnvironmentAware接口的实现方法,通过aware的方式注入,此处是environment对象
     * @param environment
     */
    @Override
    public void setEnvironment(Environment environment) {
        logger.info("开始注册数据源");
        this.evn = environment;
        // 绑定配置器
        binder = Binder.get(evn);
    }
}
继承AbstractRoutingDataSource:
public class DynamicRoutingDataSource extends AbstractRoutingDataSource {
    private static Logger logger = LoggerFactory.getLogger(DynamicRoutingDataSource.class);

    @Override
    protected Object determineCurrentLookupKey() {

        String dataSourceName = DynamicDataSourceContextHolder.getDataSourceRouterKey();
        //logger.info("当前数据源是:{}", dataSourceName);
        return DynamicDataSourceContextHolder.getDataSourceRouterKey();
    }
}
定义注解,定义切面:
@Target({ElementType.METHOD, ElementType.TYPE, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface UsedDataSource {
    String value() default "master"; //该值即key值
}
@Aspect
@Component
public class DynamicDataSourceAspect {
    private static final Logger logger = LoggerFactory.getLogger(DynamicDataSourceAspect.class);

    @Before("@annotation(ds)")
    public void changeDataSource(JoinPoint point, UsedDataSource ds) throws Throwable {
        String dsId = ds.value();
        if (DynamicDataSourceContextHolder.dataSourceIds.contains(dsId)) {
            DynamicDataSourceContextHolder.removeDataSourceRouterKey();
            //logger.info("使用数据源 :{} >", dsId, point.getSignature());
            DynamicDataSourceContextHolder.setDataSourceRouterKey(dsId);
        } else {
            logger.info("数据源[{}]不存在,使用默认数据源 >{}", dsId, point.getSignature());
            DynamicDataSourceContextHolder.setDataSourceRouterKey("master");
        }

    }

    @After("@annotation(ds)")
    public void restoreDataSource(JoinPoint point, UsedDataSource ds) {
        DynamicDataSourceContextHolder.removeDataSourceRouterKey();
    }

}

最后更改以下入口程序WebApplication。
因为跨模块了,指定一下用到的Bean/Entity/Repositories扫描;
引入了数据源的注册类;
builder.sources应该是为了打成war包才需要,记不太清楚;

@Import(DynamicDataSourceRegister.class)
@EntityScan(basePackages = "com.funwe.dao.entity")
@EnableJpaRepositories(basePackages = "com.funwe.dao.repository")
@SpringBootApplication(scanBasePackages = "com.funwe")
public class WebApplication extends SpringBootServletInitializer {

    public static void main(String[] args) {
        SpringApplication.run(WebApplication.class, args);
    }

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder){
        //指定Spring配置
        return builder.sources(WebApplication.class);
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值