springboot整合druid及多數(shù)據(jù)源配置的demo
前言
本篇主要分兩部分 ①springboot整合druid的代碼配置,以及druid的監(jiān)控頁(yè)面演示;②對(duì)實(shí)際場(chǎng)景中多數(shù)據(jù)源的配置使用進(jìn)行講解。
一、springboot整合druid的演示demo
可以用idea快速生成一個(gè)可運(yùn)行的demo工程,具體可以參考如何快速創(chuàng)建springboot項(xiàng)目
主要用到的依賴如下:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>配置數(shù)據(jù)庫(kù)需要的配置文件application.yml(注意格式和空格)
spring:
datasource:
username: root
password: root
url: jdbc:mysql://localhost:3306/firsttest?serverTimezone=UTC&useUnicode=true@characterEncoding=utf-8
driver-class-name: com.mysql.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
poolPreparedStatements: true
#配置監(jiān)控統(tǒng)計(jì)攔截的filters,stat:監(jiān)控統(tǒng)計(jì)、log4j:日志記錄、wall:防御sql注入
#如果允許時(shí)報(bào)錯(cuò) java.lang.ClassNotFoundException: org.apache.log4j.Priority
#則導(dǎo)入 log4j 依賴即可,Maven 地址: https://mvnrepository.com/artifact/log4j/log4j filters: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500編寫durid的啟動(dòng)配置類,加載數(shù)據(jù)庫(kù)信息,和druid監(jiān)控頁(yè)面的初始化工作
package com.czing.jdbcdemo.config;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
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 javax.servlet.Servlet;
import javax.sql.DataSource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
@Configuration
public class DruidConfig {
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource druidDataSource(){
return new DruidDataSource();
}
/**
* @Author wangchengzhi
* @Description
* 向DruidConfig中添加代碼,配置druid監(jiān)控管理臺(tái)的servlet
* @Date 22:12 2023/5/10
* @Param
* @return
**/
@Bean
public ServletRegistrationBean druidServletRegistrationBean(){
ServletRegistrationBean<Servlet> servletRegistrationBean = new ServletRegistrationBean<>(new StatViewServlet(),"/druid/*");
Map<String,String> initParams = new HashMap<>();
initParams.put("loginUsername","root");
initParams.put("loginPassword","root");
//后臺(tái)允許誰可以訪問
//initParams.put("allow", "localhost"):表示只有本機(jī)可以訪問
//initParams.put("allow", ""):為空或者為null時(shí),表示允許所有訪問
initParams.put("allow","");
//deny:Druid 后臺(tái)拒絕誰訪問
//initParams.put("msb", "192.168.1.20");表示禁止此ip訪問
servletRegistrationBean.setInitParameters(initParams);
return servletRegistrationBean;
}
@Bean
public FilterRegistrationBean webStatFilter() {
FilterRegistrationBean bean = new FilterRegistrationBean();
bean.setFilter(new WebStatFilter());
//exclusions:設(shè)置哪些請(qǐng)求進(jìn)行過濾排除掉,從而不進(jìn)行統(tǒng)計(jì)
Map<String, String> initParams = new HashMap<>();
initParams.put("exclusions", "*.js,*.css,/druid/*");
bean.setInitParameters(initParams);
//"/*" 表示過濾所有請(qǐng)求
bean.setUrlPatterns(Arrays.asList("/*"));
return bean;
}
}編寫controller類進(jìn)行測(cè)試(此處使用jdbcTemplate進(jìn)行演示)
package com.czing.jdbcdemo.controller;
import com.czing.jdbcdemo.mult.DataSource;
import com.czing.jdbcdemo.mult.DataSourceType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
@RestController
public class JDBCController {
@Autowired
JdbcTemplate jdbcTemplate;
/**
* @Author wangchengzhi
* @Description
* 使用springboot自帶的jdbcTemplate實(shí)現(xiàn)數(shù)據(jù)庫(kù)操作
* @Date 21:34 2023/5/10
* @Param
* @return
**/
@RequestMapping("/selectTest")
public List<Map<String, Object>> getTestAccount(){
String sql ="select * from account";
List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
return maps;
}
}啟動(dòng)項(xiàng)目,演示效果
項(xiàng)目啟動(dòng)日志:

druid的監(jiān)控頁(yè)面訪問http://localhost:8080/druid/sql.html


二、druid多數(shù)據(jù)源的配置使用
修改application.yml文件
spring:
datasource:
local:
username: root
password: root
#注意多數(shù)據(jù)源配置的時(shí)候此處為jdbc-url
jdbc-url: jdbc:mysql://localhost:3306/firsttest?serverTimezone=UTC&useUnicode=true@characterEncoding=utf-8
driver-class-name: com.mysql.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
remote:
username: root
password: root
jdbc-url: jdbc:mysql://localhost:3306/test?serverTimezone=UTC&useUnicode=true@characterEncoding=utf-8
driver-class-name: com.mysql.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource編寫多數(shù)據(jù)源的配置類:
package com.czing.jdbcdemo.config;
import com.czing.jdbcdemo.mult.DataSourceType;
import com.czing.jdbcdemo.mult.DynamicDataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;
@Configuration
public class DataSourceConfig {
@Bean
@ConfigurationProperties("spring.datasource.remote")
public DataSource remoteDataSource() {
return DataSourceBuilder.create().build();
}
@Bean
@ConfigurationProperties("spring.datasource.local")
public DataSource localDataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "dynamicDataSource")
@Primary
public DynamicDataSource dataSource(DataSource remoteDataSource, DataSource localDataSource) {
Map<Object, Object> targetDataSources = new HashMap<>();
targetDataSources.put(DataSourceType.REMOTE.name(), remoteDataSource);
targetDataSources.put(DataSourceType.LOCAL.name(), localDataSource);
return new DynamicDataSource(remoteDataSource, targetDataSources);
}
}使用自定義注解,在查詢方法的時(shí)候指定對(duì)應(yīng)的數(shù)據(jù)源:
編寫枚舉類,用于指定數(shù)據(jù)源
package com.czing.jdbcdemo.mult;
public enum DataSourceType {
REMOTE,
LOCAL
}數(shù)據(jù)源切換的處理類
package com.czing.jdbcdemo.mult;
public class DynamicDataSourceContextHolder {
/**
* 使用ThreadLocal維護(hù)變量,ThreadLocal為每個(gè)使用該變量的線程提供獨(dú)立的變量副本,
* 所以每一個(gè)線程都可以獨(dú)立地改變自己的副本,而不會(huì)影響其它線程所對(duì)應(yīng)的副本。
*/
private static final ThreadLocal<String> CONTEXT_HOLDER = new ThreadLocal<>();
/**
* 設(shè)置數(shù)據(jù)源變量
* @param dataSourceType
*/
public static void setDataSourceType(String dataSourceType){
System.out.printf("切換到{%s}數(shù)據(jù)源", dataSourceType);
CONTEXT_HOLDER.set(dataSourceType);
}
/**
* 獲取數(shù)據(jù)源變量
* @return
*/
public static String getDataSourceType(){
return CONTEXT_HOLDER.get();
}
/**
* 清空數(shù)據(jù)源變量
*/
public static void clearDataSourceType(){
CONTEXT_HOLDER.remove();
}
}數(shù)據(jù)源信息加載的實(shí)現(xiàn)
package com.czing.jdbcdemo.mult;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import javax.sql.DataSource;
import java.util.Map;
public class DynamicDataSource extends AbstractRoutingDataSource {
public DynamicDataSource(DataSource defaultTargetDataSource, Map<Object, Object> targetDataSources) {
super.setDefaultTargetDataSource(defaultTargetDataSource);
super.setTargetDataSources(targetDataSources);
// afterPropertiesSet()方法調(diào)用時(shí)用來將targetDataSources的屬性寫入resolvedDataSources中的
super.afterPropertiesSet();
}
/**
* @Author wangchengzhi
* @Description
* 根據(jù)Key獲取數(shù)據(jù)源的信息
* @Date 23:06 2023/5/10
* @Param
* @return
**/
@Override
protected Object determineCurrentLookupKey() {
return DynamicDataSourceContextHolder.getDataSourceType();
}
}多數(shù)據(jù)源的配置啟動(dòng)類,注入數(shù)據(jù)庫(kù)配置信息
package com.czing.jdbcdemo.config;
import com.czing.jdbcdemo.mult.DataSourceType;
import com.czing.jdbcdemo.mult.DynamicDataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;
@Configuration
public class DataSourceConfig {
@Bean
@ConfigurationProperties("spring.datasource.remote")
public DataSource remoteDataSource() {
return DataSourceBuilder.create().build();
}
@Bean
@ConfigurationProperties("spring.datasource.local")
public DataSource localDataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "dynamicDataSource")
@Primary
public DynamicDataSource dataSource(DataSource remoteDataSource, DataSource localDataSource) {
Map<Object, Object> targetDataSources = new HashMap<>();
targetDataSources.put(DataSourceType.REMOTE.name(), remoteDataSource);
targetDataSources.put(DataSourceType.LOCAL.name(), localDataSource);
return new DynamicDataSource(remoteDataSource, targetDataSources);
}
}自定義注解
package com.czing.jdbcdemo.mult;
import java.lang.annotation.*;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface DataSource {
/**
* 切換數(shù)據(jù)源名稱
*/
DataSourceType value() default DataSourceType.REMOTE;
}AOP攔截類的實(shí)現(xiàn)
package com.czing.jdbcdemo.mult;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
/**
* @Description TODO
* @Author wangchengzhi
* @Date 2023/5/11 10:09
*/
@Aspect
@Order(1)
@Component
public class DataSourceAspect {
@Pointcut("@annotation(com.czing.jdbcdemo.mult.DataSource)")
public void dsPointCut() {
}
@Around("dsPointCut()")
public Object around(ProceedingJoinPoint point) throws Throwable {
MethodSignature signature = (MethodSignature) point.getSignature();
Method method = signature.getMethod();
DataSource dataSource = method.getAnnotation(DataSource.class);
if (dataSource != null) {
DynamicDataSourceContextHolder.setDataSourceType(dataSource.value().name());
}
try {
return point.proceed();
} finally {
// 銷毀數(shù)據(jù)源 在執(zhí)行方法之后
DynamicDataSourceContextHolder.clearDataSourceType();
}
}
}controller測(cè)試類的編寫驗(yàn)證
package com.czing.jdbcdemo.controller;
import com.czing.jdbcdemo.mult.DataSource;
import com.czing.jdbcdemo.mult.DataSourceType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
@RestController
public class JDBCController {
@Autowired
JdbcTemplate jdbcTemplate;
/**
* @Author wangchengzhi
* @Description
* 使用springboot自帶的jdbcTemplate實(shí)現(xiàn)數(shù)據(jù)庫(kù)操作
* @Date 21:34 2023/5/10
* @Param
* @return
**/
@RequestMapping("/selectTest")
@DataSource(value=DataSourceType.LOCAL)
public List<Map<String, Object>> getTestAccount(){
String sql ="select * from account";
List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
return maps;
}
/**
* @Author wangchengzhi
* @Description
* 使用springboot自帶的jdbcTemplate實(shí)現(xiàn)數(shù)據(jù)庫(kù)操作
* @Date 21:34 2023/5/10
* @Param
* @return
**/
@RequestMapping("/selectRemote")
@DataSource(DataSourceType.REMOTE)
public List<Map<String, Object>> getRemoteAccount(){
String sql ="select * from account";
List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
return maps;
}
}啟動(dòng)項(xiàng)目,分別訪問兩個(gè)接口查詢不同的數(shù)據(jù)源
http://localhost:8080/selectTest的訪問數(shù)據(jù):

http://localhost:8080/selectRemote的訪問數(shù)據(jù)


結(jié)語
以上為springboot實(shí)現(xiàn)druid配置查詢的demo,并且演示了如何實(shí)現(xiàn)多數(shù)據(jù)源配置動(dòng)態(tài)切換的代碼實(shí)現(xiàn),注意多數(shù)據(jù)源配置的時(shí)候url的配置為jdbc-url
到此這篇關(guān)于springboot整合druid及多數(shù)據(jù)源配置的文章就介紹到這了,更多相關(guān)springboot整合druid內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
java對(duì)象和json的來回轉(zhuǎn)換知識(shí)點(diǎn)總結(jié)
在本篇文章里小編給大家分享了一篇關(guān)于java對(duì)象和json的來回轉(zhuǎn)換知識(shí)點(diǎn)總結(jié)內(nèi)容,有興趣的朋友們可以學(xué)習(xí)下。2021-01-01
Spring 實(shí)現(xiàn)excel及pdf導(dǎo)出表格示例
本篇文章主要介紹了Spring 實(shí)現(xiàn)excel及pdf導(dǎo)出表格示例,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-03-03
mybatis通過XML的方式拼接動(dòng)態(tài)sql
動(dòng)態(tài)SQL是一種在運(yùn)行時(shí)構(gòu)造和執(zhí)行SQL語句的技術(shù),這篇文章主要為大家介紹了mybatis如何通過XML的方式拼接動(dòng)態(tài)sql,有需要的小伙伴可以參考一下2024-12-12
swagger2和knife4j的詳細(xì)使用教程(入門級(jí))
最近項(xiàng)目中用到了Swagger2和knife4j作為接口文檔,所以下面這篇文章主要給大家介紹了關(guān)于swagger2和knife4j的詳細(xì)使用教程,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-09-09
關(guān)于@RequestParam的使用所遇到的404問題
這篇文章主要介紹了關(guān)于@RequestParam的使用所遇到的404問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-08-08
SpringBoot集成thymeleaf渲染html模板的步驟詳解
這篇文章主要給大家詳細(xì)介紹了SpringBoot集成thymeleaf如何使實(shí)現(xiàn)html模板的渲染,文中有詳細(xì)的代碼示例,具有一定的參考價(jià)值,需要的朋友可以參考下2023-06-06

