dynamic-datasource 集合Druid-Mybatis(四)

一个基于springboot的快速集成多数据源的启动器
浏览官网

集成Druid

springBoot2.x默认使用HikariCP,但在国内Druid的使用者非常庞大,此项目特地对其进行了适配,完成多数据源下使用Druid进行监控。

注意:主从可以使用不同的数据库连接池,如master使用Druid监控,从库使用HikariCP。 如果不配置连接池type类型,默认是Druid优先于HikariCP。

脚本初始化

在 MySQL 使用 33063307 两个端口实现主从库。

1
2
3
4
5
6
7
8
9
10
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(30) NOT NULL AUTO_INCREMENT,
`name` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`age` int(30) NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;

添加依赖

父模块 pom.xml

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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.ray</groupId>
<artifactId>dynamic-datasource</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>dynamic-datasource</name>
<description>一个基于springboot的快速集成多数据源的启动器</description>

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.5.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>

<modules>
<module>dynamic-mybatisplus3-sample</module>
<module>dynamic-mybatis-sample</module>
<module>dynamic-druid-mybatis-sample</module>
</modules>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>

<dependencies>
<!--Dynamic-datasource-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>2.2.3</version>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.0</version>
</dependency>

</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

子模块 pom.xml

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
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<artifactId>dynamic-druid-mybatis-sample</artifactId>

<description>dynamic-druid-mybatis-sample</description>

<parent>
<groupId>com.ray</groupId>
<artifactId>dynamic-datasource</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>

<dependencies>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>

<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>

</dependencies>

</project>

实体类

User.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package com.ray.dynamicdruidmybatissample.entity;

import lombok.Data;

/**
* @author Ray
* @date 2018/10/10
* 用户实体类
*/
@Data
public class User {

private Integer id;
private String name;
private Integer age;
}

数据访问层

UserMapper.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package com.ray.dynamicdruidmybatissample.mapper;

import com.ray.dynamicdruidmybatissample.entity.User;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

/**
* @author Ray
* @date 2018/10/10
* 数据访问层
*/
//@DS("slave")这里可以使用但不建议,不要和service同时使用
public interface UserMapper {

@Insert("INSERT INTO user (name,age) values (#{name},#{age})")
boolean addUser(@Param("name") String name, @Param("age") Integer age);

@Select("SELECT * FROM user")
List<User> selectUsers();
}

数据服务层

UserService.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package com.ray.dynamicdruidmybatissample.service;

import com.ray.dynamicdruidmybatissample.entity.User;

import java.util.List;

/**
* @author Ray
* @date 2018/10/10
* 数据服务层
*/
public interface UserService {

void addUser(User user);

List selectUser();
}

实现层

UserServiceImpl.java

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
package com.ray.dynamicdruidmybatissample.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.ray.dynamicdruidmybatissample.entity.User;
import com.ray.dynamicdruidmybatissample.mapper.UserMapper;
import com.ray.dynamicdruidmybatissample.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
* @author Ray
* @date 2018/10/10
* 服务实现层
*/
@Service
@DS("slave")
public class UserServiceImpl implements UserService {

@Autowired
private UserMapper userMapper;

/**
* 默认是master可以省略这个注解,如果在类上注解了其他库,则@DS("master")不能省略
*/
@DS("master")
@Override
public void addUser(User user) {
userMapper.addUser(user.getName(), user.getAge());
}

@Override
public List selectUser() {
return userMapper.selectUsers();
}
}

启动类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package com.ray.dynamicdruidmybatissample;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication(exclude = DruidDataSourceAutoConfigure.class)
@MapperScan("com.ray.dynamicdruidmybatissample.mapper")
public class DynamicDruidMybatisSampleApplication {

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

注意: 排除 原生Druid的快速配置类。

为什么要排除DruidDataSourceAutoConfigure ?

DruidDataSourceAutoConfigure会注入一个DataSourceWrapper,其会在原生的spring.datasource下找url,username,password等。而我们动态数据源的配置路径是变化的。

如果遇到DruidDataSourceAutoConfigure抛出no suitable driver表示注解排除没有生效尝试以下这种排除方法

1
2
3
spring:
autoconfigure:
exclude: com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure

配置文件

application.yml

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
spring:
datasource:
dynamic:
druid: #以下是全局默认值,可以全局更改
initial-size: 0
max-active: 8
min-idle: 2
max-wait: -1
min-evictable-idle-time-millis: 30000
max-evictable-idle-time-millis: 30000
time-between-eviction-runs-millis: 0
validation-query: select 1
validation-query-timeout: -1
test-on-borrow: false
test-on-return: false
test-while-idle: true
pool-prepared-statements: true
max-open-prepared-statements: 100
filters: stat,wall
share-prepared-statements: true
datasource:
master:
username: root
password: root
url: jdbc:mysql://localhost:3306/dynamic?useSSL=false
driver-class-name: com.mysql.jdbc.Driver
druid: #这里可以重写默认值
initial-size: 5
slave:
username: root
password: root
url: jdbc:mysql://localhost:3307/dynamic?useSSL=false
driver-class-name: com.mysql.jdbc.Driver
logging:
level:
com.ray: debug

其他属性依旧如原生druid-spring-boot-starter的配置。

测试类

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
package com.ray.dynamicdruidmybatissample;

import com.ray.dynamicdruidmybatissample.entity.User;
import com.ray.dynamicdruidmybatissample.service.UserService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.Random;

@RunWith(SpringRunner.class)
@SpringBootTest
public class DynamicDruidMybatisSampleApplicationTests {

private Random random = new Random();

@Autowired
private UserService userService;

@Test
public void testAddUser() {
User user = new User();
user.setName("测试用户" + random.nextInt());
user.setAge(random.nextInt(100));
userService.addUser(user);
}

@Test
public void testSelectUser() {
userService.selectUser();
}
}

测试结果

1
2
3
4
5
6
7
2018-10-10 09:32:29.547  INFO 4848 --- [           main] com.alibaba.druid.pool.DruidDataSource   : {dataSource-1} inited
2018-10-10 09:32:29.556 INFO 4848 --- [ main] com.alibaba.druid.pool.DruidDataSource : {dataSource-2} inited
2018-10-10 09:32:29.556 INFO 4848 --- [ main] c.b.d.d.DynamicRoutingDataSource : 初始共加载 2 个数据源
2018-10-10 09:32:29.556 INFO 4848 --- [ main] c.b.d.d.DynamicRoutingDataSource : 添加数据源 slave 成功
2018-10-10 09:32:29.556 INFO 4848 --- [ main] c.b.d.d.DynamicRoutingDataSource : 添加数据源 master 成功
2018-10-10 09:32:29.557 INFO 4848 --- [ main] c.b.d.d.DynamicRoutingDataSource : 当前的默认数据源是单数据源,数据源名为master
……

数据库 建议 只执行 INSERT UPDATE DELETE 操作。

1
2
3
2018-10-10 09:32:31.711 DEBUG 4848 --- [           main] c.r.d.mapper.UserMapper.addUser          : ==>  Preparing: INSERT INTO user (name,age) values (?,?) 
2018-10-10 09:32:32.061 DEBUG 4848 --- [ main] c.r.d.mapper.UserMapper.addUser : ==> Parameters: 测试用户-786781291(String), 34(Integer)
2018-10-10 09:32:32.157 DEBUG 4848 --- [ main] c.r.d.mapper.UserMapper.addUser : <== Updates: 1

数据库 建议 只执行 SELECT 操作。

1
2
3
2018-10-10 09:32:32.192 DEBUG 4848 --- [           main] c.r.d.mapper.UserMapper.selectUsers      : ==>  Preparing: SELECT * FROM user 
2018-10-10 09:32:32.207 DEBUG 4848 --- [ main] c.r.d.mapper.UserMapper.selectUsers : ==> Parameters:
2018-10-10 09:32:32.234 DEBUG 4848 --- [ main] c.r.d.mapper.UserMapper.selectUsers : <== Total: 0