本文将会介绍SpringBoot集成Mybatis,主要关注DataSource的配置
然后引入Druid数据库连接池,最后使用Zookeeper实现数据源的动态配置
3.1.SpringBoot集成Mybatis
3.1.1.添加依赖包
添加项目依赖包;SpringBoot、Mybatis、Mysql连接等
spring-boot-starter-parent
org.springframework.boot
2.3.12.RELEASE
4.0.0
org.poiuy
1.0-SNAPSHOT
springboot-datasource-mybatis
11
11
org.springframework.boot
spring-boot-starter-web
2.3.12.RELEASE
spring-boot-starter-logging
org.springframework.boot
org.springframework.boot
spring-boot-starter-log4j2
2.5.2
mysql
mysql-connector-java
8.0.26
org.mybatis.spring.boot
mybatis-spring-boot-starter
2.1.3
org.mybatis
mybatis-typehandlers-jsr310
1.0.2
org.springframework.boot
spring-boot-starter-validation
2.3.11.RELEASE
3.1.2.添加SpringBoot配置文件
SpringBoot配置文件,添加datasource和mybatis的配置
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: xxx
url: jdbc:mysql://192.168.1.208:9906/poiuy_study?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
mybatis:
mapper-locations: classpath:mapper/*.xml
type-aliases-package: org.poiuy.springboot.datasource.mybatis.domain
3.1.3.添加Domain类
添加数据对象
public class MybatisUser {
private Integer userId;
@NotNull(message = "用户名不能为空")
private String username;
private String secure;
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getSecure() {
return secure;
}
public void setSecure(String secure) {
this.secure = secure;
}
}
3.1.4.添加Mapper
mapper接口中添加一个查询用户方法
@Mapper
public interface MybatisUserMapper {
MybatisUser selectByUsername(@Param("username") String username);
}
对应的xml文件
3.1.5.Service接口
service接口直接调用mapper方法
@Service("mybatisUserService")
public class MybatisUserServiceImpl implements MybatisUserService {
private final MybatisUserMapper mybatisUserMapper;
@Autowired
public MybatisUserServiceImpl(MybatisUserMapper mybatisUserMapper) {
this.mybatisUserMapper = mybatisUserMapper;
}
@Override
public MybatisUser getUserByUsername(String username) {
return mybatisUserMapper.selectByUsername(username);
}
}
3.1.6.Controller控制器
user控制器
@RestController
@RequestMapping("/user")
public class UserController {
private final Logger logger = LogManager.getLogger(getClass());
private final MybatisUserService mybatisUserService;
@Autowired
public UserController(MybatisUserService mybatisUserService){
this.mybatisUserService = mybatisUserService;
}
@PostMapping
public R getByUsername(@RequestBody @Valid MybatisUser mybatisUser){
String username = mybatisUser.getUsername();
logger.debug("获取到参数:{}",username);
MybatisUser dbUser = mybatisUserService.getUserByUsername(username);
return R.ok().put("data",dbUser);
}
}
3.1.7.测试
运行SpringBoot程序,在PostMan中调用请求

3.2.增加Druid连接池
3.2.1.添加依赖包
添加Druid的依赖包
spring-boot-starter-parent
org.springframework.boot
2.3.12.RELEASE
4.0.0
1.0-SNAPSHOT
org.poiuy
springboot-datasource-druid
11
11
org.springframework.boot
spring-boot-starter-web
2.3.12.RELEASE
spring-boot-starter-logging
org.springframework.boot
org.springframework.boot
spring-boot-starter-log4j2
2.5.2
mysql
mysql-connector-java
8.0.26
org.mybatis.spring.boot
mybatis-spring-boot-starter
2.1.3
com.alibaba
druid-spring-boot-starter
1.2.5
org.springframework.boot
spring-boot-starter-validation
2.4.0
3.2.2.修改SpringBoot配置文件
SpringBoot配置文件,删除原来的Datasource配置,并增加Druid
Druid分为基础配置、监控配置和连接池参数配置。可根据需要进行配置
spring:
datasource:
# 切换数据源
type: com.alibaba.druid.pool.DruidDataSource
druid:
# Druid基础配置 , 与DataSource配置等同的效果
username: root
password: xxx
url: jdbc:mysql://192.168.1.208:9906/poiuy_study?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
driver-class-name: com.mysql.cj.jdbc.Driver
# Druid监控
filter:
stat:
log-slow-sql: true
slow-sql-millis: 1000
merge-sql: false
wall:
config:
multi-statement-allow: true
web-stat-filter:
enabled: true
url-pattern: /*
exclusions: /druid/*,*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico
session-stat-enable: true
session-stat-max-count: 10
principal-session-name: session_name
principal-cookie-name: cookie_name
profile-enable:
stat-view-servlet:
enabled: true
url-pattern: /druid/*
reset-enable: false
login-username: poiuy
login-password: 123456
allow: 127.0.0.1,192.168.1.111
deny:
aop-patterns:
#连接池配置
name: testDruidDataSource
initial-size: 10
max-active: 20
min-idle: 10
max-wait: 60000
pool-prepared-statements: true
max-pool-prepared-statement-per-connection-size: 20
validation-query: SELECT 1 FROM DUAL
validation-query-timeout: 3000
test-on-borrow: false
test-on-return: false
test-while-idle: true
time-between-eviction-runs-millis: 5000
min-evictable-idle-time-millis: 5000
max-evictable-idle-time-millis: 5000
mybatis:
mapper-locations: classpath:mapper/*.xml
type-aliases-package: org.poiuy.springboot.datasource.mybatis.domain
3.2.3.测试
运行SpringBoot程序,在PostMan中调用请求

另外如果配置了Druid监控配置项,那么在浏览器输入
http://localhost:8080/druid/index.html
可以进入Druid的监控界面

3.3.Zookeeper实现数据源的动态配置
3.3.1.添加依赖包
在pom.xml中新增curator依赖包
spring-boot-starter-parent
org.springframework.boot
2.3.12.RELEASE
4.0.0
org.poiuy
1.0-SNAPSHOT
springboot-datasource-dynamic
11
11
org.springframework.boot
spring-boot-starter-web
2.3.12.RELEASE
spring-boot-starter-logging
org.springframework.boot
org.springframework.boot
spring-boot-starter-log4j2
2.5.2
org.mybatis.spring.boot
mybatis-spring-boot-starter
2.1.3
mysql
mysql-connector-java
8.0.26
com.alibaba
druid-spring-boot-starter
1.2.5
org.apache.curator
curator-recipes
2.11.0
org.springframework.boot
spring-boot-starter-validation
2.3.12.RELEASE
com.google.code.gson
gson
2.8.8
3.3.2.SpringBoot配置文件
修改SpringBoot配置文件,将Druid的基础配置进行注释,并添加Zookeeper配置项
spring:
datasource:
# 切换数据源
type: com.alibaba.druid.pool.DruidDataSource
druid:
# Druid基础配置 , 与DataSource配置等同的效果
# username: root
# password: xxx
# url: jdbc:mysql://192.168.1.208:9906/poiuy_study?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
# driver-class-name: com.mysql.cj.jdbc.Driver
# Druid监控
filter:
stat:
log-slow-sql: true
slow-sql-millis: 1000
merge-sql: false
wall:
config:
multi-statement-allow: true
web-stat-filter:
enabled: true
url-pattern: /*
exclusions: /druid/*,*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico
session-stat-enable: true
session-stat-max-count: 10
principal-session-name: session_name
principal-cookie-name: cookie_name
profile-enable:
stat-view-servlet:
enabled: true
url-pattern: /druid/*
reset-enable: false
login-username: poiuy
login-password: 123456
allow: 127.0.0.1,192.168.1.111
deny:
aop-patterns:
#连接池配置
name: testDruidDataSource
initial-size: 10
max-active: 20
min-idle: 10
max-wait: 60000
pool-prepared-statements: true
max-pool-prepared-statement-per-connection-size: 20
validation-query: SELECT 1 FROM DUAL
validation-query-timeout: 3000
test-on-borrow: false
test-on-return: false
test-while-idle: true
time-between-eviction-runs-millis: 5000
min-evictable-idle-time-millis: 5000
max-evictable-idle-time-millis: 5000
mybatis:
mapper-locations: classpath:mapper/*.xml
type-aliases-package: org.poiuy.springboot.datasource.mybatis.domain
zookeeper:
connectString: 192.168.1.208:2181
connectionTimeoutMs: 5000
maxRetries: 3
baseSleepTimeMs: 1000
listenerPath: /zookeeper/datasource
3.3.3.集成Zookeeper
创建ZookeeperConfig,将CuratorFramework注入到Spring中,用来操作Zookeeper
@Configuration
public class ZookeeperConfig {
@Value("${zookeeper.connectString}")
private String connectString;
@Value("${zookeeper.connectionTimeoutMs}")
private Integer connectionTimeoutMs;
@Value("${zookeeper.maxRetries}")
private Integer maxRetries;
@Value("${zookeeper.baseSleepTimeMs}")
private Integer baseSleepTimeMs;
private CuratorFramework client;
@PostConstruct
public void init(){
client = CuratorFrameworkFactory.builder()
.connectString(connectString)
.connectionTimeoutMs(connectionTimeoutMs)
.retryPolicy(new ExponentialBackoffRetry(baseSleepTimeMs, maxRetries))
.build();
//连接
client.start();
}
@Bean
public CuratorFramework curatorFramework(){
return this.client;
}
}
3.3.4.定义DataSource配置
此时需要重新构建DruidDataSource对象,在生成dataSource时从zookeeper中获取配置信息,并赋值到DataSource
这里只写了基本的4个参数,注意此时需要将Spring配置文件中相同的属性删除,否则会被Spring配置文件中的值覆盖掉
@Configuration
public class DruidConfig {
private final Logger logger = LogManager.getLogger(getClass());
@Resource
private CuratorFramework curatorFramework;
@Value("${zookeeper.listenerPath}")
private String datasourceParh;
@ConfigurationProperties(prefix = "spring.datasource.druid")
@Bean
public DataSource dataSource(){
DruidDataSource druidDataSource = new DruidDataSource();
try {
byte[] datasourceData = curatorFramework.getData().forPath(datasourceParh);
String datasourceJson = new String(datasourceData);
logger.debug("获取到zookeeper的数据:{}",datasourceJson);
Gson gson = new GsonBuilder().serializeNulls().create();
ZookeeperDataSource zookeeperDataSource = gson.fromJson(datasourceJson,ZookeeperDataSource.class);
if(zookeeperDataSource == null) {
return druidDataSource;
}
druidDataSource.setUrl(zookeeperDataSource.getUrl());
druidDataSource.setUsername(zookeeperDataSource.getUsername());
druidDataSource.setPassword(zookeeperDataSource.getPassword());
druidDataSource.setDriverClassName(zookeeperDataSource.getDriver());
} catch (Exception e) {
e.printStackTrace();
}
return druidDataSource;
}
}
Zookeeper上配置的数据源信息,直接存储了json数据

此时启动项目,在PostMan中调用接口测试
虽然SpringBoot的配置文件中没有配置数据源基本信息,但程序依旧运行正常

3.3.5.动态修改数据源
添加Zookeeper监听器,当数据节点的值发生变化时重新启动DataSource并设置修改后的值
@Component
public class ZookeeperListener {
private static Logger logger = LogManager.getLogger(ZookeeperListener.class);
@Value("${zookeeper.listenerPath}")
private String listenerPath;
@Resource
private CuratorFramework client;
@Resource
private DruidDataSource dataSource;
@PostConstruct
public void start() throws Exception {
//创建监听
PathChildrenCache cache = new PathChildrenCache(client, "/zookeeper",true);
cache.start();
cache.rebuild();
cache.getListenable().addListener((CuratorFramework curatorFramework, PathChildrenCacheEvent pathChildrenCacheEvent) -> {
PathChildrenCacheEvent.Type type = pathChildrenCacheEvent.getType();
ChildData data = pathChildrenCacheEvent.getData();
List initialData = pathChildrenCacheEvent.getInitialData();
logger.debug("节点发生变化,type = {} data = {} initialData = {}",type,data,initialData);
if(data != null && listenerPath.equals(data.getPath())) {
byte[] datasourceData = data.getData();
String datasourceJson = new String(datasourceData);
logger.debug("获取到zookeeper的数据:{}",datasourceJson);
Gson gson = new GsonBuilder().serializeNulls().create();
ZookeeperDataSource zookeeperDataSource = gson.fromJson(datasourceJson,ZookeeperDataSource.class);
if(zookeeperDataSource != null) {
dataSource.restart();
dataSource.setUrl(zookeeperDataSource.getUrl());
dataSource.setUsername(zookeeperDataSource.getUsername());
dataSource.setPassword(zookeeperDataSource.getPassword());
dataSource.setDriverClassName(zookeeperDataSource.getDriver());
}
}
});
}
}
这里为了测试,新建了一个数据库,测试动态数据库的变更
重新启动程序,调用接口,程序运行正常(注意此时返回的id为1)

然后通过Zookeeper客户端修改datasource的值(此处仅修改了database)
set /zookeeper/datasource {"username":"xxx","password":"xxx","url":"jdbc:mysql://192.168.1.208:9906/poiuy_study_bak?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai","driver":"com.mysql.cj.jdbc.Driver"}
在程序后台console中可以看到Zookeeper监听到数据变化后重新获取数据源配置并重启DruidDataSource

此时再次调用接口可以看到获取的值是更换后的数据库的数据
