双数据源实现
01 添加必要的依赖
- spring-boot-starter
- mybatis-plus-boot-starter
- dynamic-datasource-spring-boot-starter # 配置动态数据源
- druid-spring-boot-starter # 阿里的数据库连接池
- 数据库驱动
- lombok
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.1</version>
</dependency>
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>sqljdbc4</artifactId>
<version>4.0</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.20</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>2.5.6</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
<scope>provided</scope>
</dependency>
</dependencies>
02 配置各数据源的连接字符串
DruidDataSourceAutoConfigure 会注入一个DataSourceWrapper ,它会在原生的spring.datasource 下查找数据库的连接信息;而动态数据源的连接配置是在 dynamic 下,因此需要排除 DruidDataSourceAutoConfigure,否则会报错。
排除方式有两种:
-
在项目启动类排除。 @SpringBootApplication(exclude = DruidDataSourceAutoConfigure.class)
public class Application {
public static void main(String[] args) { SpringApplication.run(Application.class, args); }
}
-
在配置文件排除。 server:
port: 8080
spring:
datasource:
dynamic:
primary: DB_SqlServer_CS
datasource:
DB_SqlServer_ZS:
url: jdbc:sqlserver://10.20.7.50:1433;DatabaseName=measure
username: sa
password: dxyl
driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver
DB_SqlServer_CS:
url: jdbc:sqlserver://58.34.1.32:10202;DatabaseName=measure
username: sa
password: qAZ123.0
driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver
druid:
initial-size: 1
max-active: 20
min-idle: 1
max-wait: 60000
autoconfigure:
exclude: com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure
mybatis-plus:
mapper-locations: classpath*:*.xml
03 非默认数据库的service / mapper添加 @DS 注解
- @DS 可以注解在方法和类上,同时存在,那么方法注解优先于类注解。
- 不要同时在
service 和mapper 上添加注解。
@Mapper
public interface Tpcca01Mapper extends BaseMapper<Tpcca01> {
String getLatestRecTime();
@DS("DB_SqlServer_ZS")
List<Tpcca01> mySelectList(@Param("ew") LambdaQueryWrapper<Tpcca01> wrapper);
}
实操过程中出现的问题
The server selected protocol version TLS10 is not accepted by client preferences [TLS13, TLS12]” 方法1: 找到jdk下的jre,之后按照下图路径找到java.security 删除jdk.tls.disabledAlgorithms 中的 TLSv1、TLSv1.1、3DES_EDE_CBC即可
方法2: 在启动类中添加
static{
try {
String property = Security.getProperty("jdk.tls.disabledAlgorithms");
String replace = property.replace("TLSv1,", "");
Security.setProperty("jdk.tls.disabledAlgorithms",replace);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
|