1:在pom文件中引入druid jar包
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>${druid.version}</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>${dynamic.datasource.version}</version>
</dependency>
2:在application.yml文件中配置数据源和druid相关属性
spring:
datasource:
dynamic:
primary: db1 #配置默认数据库
datasource:
db1: #数据源1配置
url: jdbc:mysql://localhost:3306/db1?serverTimezone=Hongkong&allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
db2: #数据源2配置
url: jdbc:mysql://localhost:3306/db2?serverTimezone=Hongkong&allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
druid:
initial-size: 15
max-active: 100
min-idle: 15
max-wait: 60000
time-between-eviction-runs-millis: 60000
min-evictable-idle-time-millis: 300000
test-on-borrow: false
test-on-return: false
test-while-idle: true
validation-query: SELECT 1
validation-query-timeout: 1000
keep-alive: true
remove-abandoned: true
remove-abandoned-timeout: 180
log-abandoned: true
pool-prepared-statements: true
max-pool-prepared-statement-per-connection-size: 20
filters: stat,wall,slf4j
use-global-data-source-stat: true
maxOpenPreparedStatements: 100
connect-properties.mergeSql: true
connect-properties.slowSqlMillis: 5000
autoconfigure:
exclude: com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure #去除druid配置
3:配置有关druid监控页面相关属性
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
/**
* @Date 2021/3/9 16:25
*/
@Configuration
public class DruidConfig {
@Bean
public ServletRegistrationBean DruidStatViewServlet(){
//org.springframework.boot.context.embedded.ServletRegistrationBean提供类的进行注册.
ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(),"/druid/*");
//添加初始化参数
//IP白名单(没有配置或者为空,则允许所有访问))
servletRegistrationBean.addInitParameter("allow","127.0.0.1");
//IP黑名单 (存在共同时,deny优先于allow)
servletRegistrationBean.addInitParameter("deny","192.168.1.124");
//登录用户名
servletRegistrationBean.addInitParameter("loginUsername","admin");
//登录密码
servletRegistrationBean.addInitParameter("loginPassword","123456");
//是否可以重置
servletRegistrationBean.addInitParameter("resetEnable","fase");
return servletRegistrationBean;
}
/**
* 注册一个:filterRegistrationBean
* @return
*/
@Bean
public FilterRegistrationBean druidStatFilter(){
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
//添加过滤规则.
filterRegistrationBean.addUrlPatterns("/*");
//添加不需要忽略的格式信息.
filterRegistrationBean.addInitParameter("exclusions","*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
return filterRegistrationBean;
}
}
4:注意事项
DruidDataSourceAutoConfigure会注入一个DataSourceWrapper,其会在原生的spring.datasource下找 url, username, password 等。动态数据源 URL 等配置是在 dynamic 下,因此需要排除,否则会报错。排除方式有两种,一种是上述application.yml配置文件排除,还有一种可以在项目启动类排除:
@SpringBootApplication(exclude = DruidDataSourceAutoConfigure.class)
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
二者选其一即可
5:动态数据源读取操作
@DS
可以注解在方法上和类上,同时存在方法注解优先于类上注解。
注解在 service 实现或 mapper 接口方法上,不要同时在 service 和 mapper 注解。
@Service
@DS("db2") //@DS 可以注解在方法上和类上,同时存在方法注解优先于类上注解。
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
@Autowired
UserMapper userMapper;
/**
*
* @param userDto
* @return
*/
@DS("db2")
@Override
public IPage<User> getSatisfaction(UserDto userDto) {
LambdaQueryWrapper<User> lambdaQueryWrapper = Wrappers.lambdaQuery();
if(userDto.getStartTime()!=null) {
lambdaQueryWrapper.ge(User::getCreateTime, userDto.getStartTime());
}
if(satisfactionDto.getEndTime()!=null) {
lambdaQueryWrapper.le(User::getCreateTime, userDto.getEndTime());
}
Page<User> userPage = new Page<>(userDto.getPageNo() , userDto.getPageSize());
IPage<User> userIPage= userMapper.selectPage(userPage,lambdaQueryWrapper);
return userIPage;
}
@Override
@DS("db1") //使用db1数据源
public int addUser(User user) {
return userMapper.insert(user);
}
}