mybatis全注解动态数据源配置

2 篇文章 0 订阅
1 篇文章 0 订阅
核心jar
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.2.1</version>
</dependency>
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.16.16</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.26</version>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.0.12</version>
</dependency>
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>1.3.1</version>
</dependency>
<dependency>
    <groupId>org.yaml</groupId>
    <artifactId>snakeyaml</artifactId>
    <version>1.17</version>
</dependency>


 
@Configuration
@EnableTransactionManagement
public class MultiDataSource {

    @Bean
    public DynamicDataSource dynamicDataSource() {
        DynamicDataSource source = new DynamicDataSource();
        return source;
    }
    @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean(DynamicDataSource source) {

        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        SqlSessionFactoryBean sqlSessionFactory = new SqlSessionFactoryBean();
        Resource[] resources ;
        try {
            resources = resolver.getResources("classpath*:META-INF/sqlmap/*Mapper.xml");
            sqlSessionFactory.setDataSource(source);
            sqlSessionFactory.setMapperLocations(resources);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sqlSessionFactory;
    }
    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer() {
        MapperScannerConfigurer configurer = new MapperScannerConfigurer();
        configurer.setBasePackage("com.fulihui.welfarecentre.dal.mapper");
        configurer.setSqlSessionFactoryBeanName("sqlSessionFactoryBean");
        return configurer;
    }
   
}

  初始化 mybatis相关配置


public class DataSourceContextHolder {

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

    public static void setDataSource(String datasourceType){
        contextHolder.set(datasourceType);
    }

    public static String getDataSource(){
        return ((String) contextHolder.get());
    }

    public static void clear(){
        contextHolder.remove();
    }
}
  线程安全的TheadLocal来储存key


@Data
public class CustomDruidDataSource extends DruidDataSource {
    private static final long serialVersionUID = 7144084830980132474L;
    private String key;
}
 定义一个对象 继承阿里巴巴的druiDataSource

@Data
public class DataSourcesConfig {

  private List<CustomDruidDataSource> dataSource;

}
因为是多个数据源 所以又创建了一个对象 来顶一个list来接收 自定义的数据源

下面来实现 dubbo服务和 web工程拿到的传来的key

  1、 dubbo服务:

         

@Activate(group = Constants.PROVIDER)
public class DubboContextFilter implements Filter {

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

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        Object[] arguments = invocation.getArguments();
        if(arguments != null && arguments.length > 0){
            for (Object argument : arguments) {
                if(argument instanceof CommonRequest){
                    checkArgs(((CommonRequest) argument).getShowModule());
                }else if(argument instanceof CommonPageRequest){
                    checkArgs(((CommonPageRequest) argument).getShowModule());
                }
                break;
            }
        }
        return invoker.invoke(invocation);
    }

    /**
     * 参数校验
     * @param platformSource
     */
    private void checkArgs(Integer platformSource){
        logger.info("dubbo context filter: platformSource={}",platformSource);
        if(platformSource == null){
            throw new RpcException("platformSource can't be empty!");
        }
        DataSourceContextHolder.setDataSource(platformSource.toString());

    }
}

在resources目录下添加纯文本文件META-INF/dubbo/com.alibaba.dubbo.rpc.Filter,内容如下:

dubboContextFilter=xx.xx.DubboContextFilter
2:web工程

使用一个动态代理,在执行这个方法的时候,我们动态的给DataSourceContextHolder设置值,我建议使用spring aop,或者如果

不是spring的项目,那么直接只用动态代理也是很好的我觉,下面贴出核心代码

@Aspect
@Component
public class DataSourceAspect {
 
    @Pointcut("execution(* com.wang.route.DynamicPersonService.*(..))")
    public void pointCut() {
    }
 
 
    @Before(value = "pointCut()")
    public void before(JoinPoint joinPoint) {
      
           
DataSourceContextHolder.setDataSource(platformSource.toString());
}}
 切换动态数据源 核心配置: 

public class DynamicDataSource extends AbstractRoutingDataSource {

    @Override
    protected Object determineCurrentLookupKey() {
        String dataSource = DataSourceContextHolder.getDataSource();
        if (StringUtil.isBlank(dataSource)) {
            logger.info("determineCurrentLookupKey: dataSource not found!");
            throw new RuntimeException("determineCurrentLookupKey: dataSource not found!");
        }
        return DataSourceContextHolder.getDataSource();
    }

    @Override
    public void afterPropertiesSet() {
        DataSourcesConfig config = null;
        Yaml yaml = new Yaml();
        try {
            config = yaml.loadAs(new FileInputStream(new File("conf/dataSource.yml")), DataSourcesConfig.class);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        if (!Objects.isNull(config)) {
            Map<Object, Object> _targetDataSources = Maps.newHashMap();
            config.getDataSource().forEach(dataSource -> {
                _targetDataSources.put(dataSource.getKey(), dataSource);
            });
            super.setTargetDataSources(_targetDataSources);
            super.afterPropertiesSet();
        }
    }
}

conf:dataSource.yml

dataSource:
 - driverClassName: com.mysql.jdbc.Driver
   url: jdbc:mysql://192.168.1.45:3306/welfare
   username: root
   password: root1234
   initialSize: 1
   minIdle: 20
   maxWait: 60000
   timeBetweenEvictionRunsMillis: 60000
   minEvictableIdleTimeMillis: 300000
   validationQuery: SELECT 'x'
   testWhileIdle: true
   testOnBorrow: false
   poolPreparedStatements: false
   maxPoolPreparedStatementPerConnectionSize: 50
   filters: stat
   defaultAutoCommit: true
   key: 0

 - driverClassName: com.mysql.jdbc.Driver
   url: jdbc:mysql://192.168.1.45:3306/welfare_1
   username: root
   password: root1234
   initialSize: 1
   minIdle: 20
   maxWait: 60000
   timeBetweenEvictionRunsMillis: 60000
   minEvictableIdleTimeMillis: 300000
   validationQuery: SELECT 'x'
   testWhileIdle: true
   testOnBorrow: false
   poolPreparedStatements: false
   maxPoolPreparedStatementPerConnectionSize: 50
   filters: stat
   defaultAutoCommit: true
   key: 1







  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Mybatis-Plus是一个基于Mybatis的增强工具,它提供了很多便捷的功能来简化开发。在使用Mybatis-Plus时,如果需要实现动态数据源的功能,可以按照以下步骤进行配置。 首先,需要创建一个自定义的动态数据源类,比如`MyDynamicDataSource`。这个类需要继承`AbstractRoutingDataSource`,并实现`determineCurrentLookupKey`方法来返回当前的数据源标识。在这个类中,可以使用`ThreadLocal`来保存当前的数据源标识,以便在不同的线程中切换数据源。同时,还需要提供设置数据源标识和清除数据源标识的方法。\[1\] 接下来,需要引入`dynamic-datasource-spring-boot-starter`的依赖,可以在`pom.xml`文件中添加以下配置: ```xml <dependency> <groupId>com.baomidou</groupId> <artifactId>dynamic-datasource-spring-boot-starter</artifactId> <version>3.5.1</version> </dependency> ```\[2\] 然后,需要创建一个配置类,比如`DataSourceConfig`,并使用`@Configuration`注解标记。在这个配置类中,可以使用`@Bean`注解来创建主数据源和从数据源,并使用`@ConfigurationProperties`注解来指定数据源配置信息。同时,还需要使用`@Primary`注解标记主数据源。最后,将主数据源和从数据源添加到`MyDynamicDataSource`中,并返回一个`MyDynamicDataSource`实例。\[3\] 通过以上配置,就可以实现Mybatis-Plus的动态数据源功能了。在使用Mybatis-Plus时,可以通过调用`MyDynamicDataSource.setDataSource`方法来设置当前的数据源标识,从而实现动态切换数据源的功能。 #### 引用[.reference_title] - *1* *3* [MyBatis Plus动态数据源](https://blog.csdn.net/qq_44802667/article/details/129247656)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [mybatis-plus动态数据源](https://blog.csdn.net/qq_41472891/article/details/123270082)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值