多数据源配置

yml配置文件如下:
复制代码
server:
  port: 8080
spring:
  datasource:
    service1:
      jdbc-url: jdbc:mysql://localhost:3306/dataBase1?characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai
      username: username
      password: 'password'
      driver-class-name: com.mysql.cj.jdbc.Driver
    service2:
      jdbc-url: jdbc:mysql://localhost:3306/dataBase2?characterEncoding=utf-8&useSSL=false&servertimezone=cst&nullCatalogMeansCurrent=true
      username: username
      password: 'password'
      driver-class-name: com.mysql.cj.jdbc.Driver
复制代码
config配置类的代码如下(以其中一个数据库为例):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
@Configuration
@MapperScan(basePackages = {"com.pandul.secret.technology.common.mapper"}, sqlSessionFactoryRef = "service1DataSourceFactory")
public class Service1DataSourceConfig {
 
    /**
     * 源,prefix要和yml文件里的一致
     */
    @Bean(name = "service1DataSource")
    @ConfigurationProperties(prefix = "spring.datasource.service1")
    public DataSource dataSource() {
        return DataSourceBuilder.create().build();
    }
 
    /**
     * 工厂
     */
    @Bean("service1DataSourceFactory")
    @DependsOn("service1DataSource")
    public SqlSessionFactory dataSourceFactory() throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource());
        return factoryBean.getObject();
    }
 
    /**
     * 模板
     */
    @Bean("service1SqlSessionTemplate")
    @DependsOn("service1DataSourceFactory")
    public SqlSessionTemplate sqlSessionTemplate(
            @Qualifier("Service1DataSourceFactory") SqlSessionFactory sessionfactory) {
        return new SqlSessionTemplate(sessionfactory);
    }
 
    // 创建事务管理器
    @Bean(name = "service1TransactionManager")
    public PlatformTransactionManager txManager(@Qualifier("service1DataSource") DataSource service1DataSource) {
        return new DataSourceTransactionManager(service1DataSource);
    }
}<em id="__mceDel"><strong><br></strong></em>
扩展(可以从nacos读取):
复制代码
spring:
  profiles:
    active: '@profiles.active@'
  application:
    name: serviceName
  cloud:
    nacos:
      discovery:
        server-addr: sys-nacos:8848
      config:
        server-addr: sys-nacos:8848
        file-extension: yml
        group: GROUPNAME
        prefix: serviceName
        ext-config[0]:
          data-id: common-datasource.yml
          group: FAWKES_SYS_GROUP
          refresh: true
复制代码

nacos上数据库配置就从common-datasource.yml里读取

1
<strong> </strong>
posted @   nitianxiaozi  阅读(18)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示