springboot整合druid及多數(shù)據(jù)源配置的demo
前言
本篇主要分兩部分 ①springboot整合druid的代碼配置,以及druid的監(jiān)控頁面演示;②對實際場景中多數(shù)據(jù)源的配置使用進行講解。
一、springboot整合druid的演示demo
可以用idea快速生成一個可運行的demo工程,具體可以參考如何快速創(chuàng)建springboot項目
主要用到的依賴如下:
<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ù)庫需要的配置文件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)計攔截的filters,stat:監(jiān)控統(tǒng)計、log4j:日志記錄、wall:防御sql注入 #如果允許時報錯 java.lang.ClassNotFoundException: org.apache.log4j.Priority #則導入 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的啟動配置類,加載數(shù)據(jù)庫信息,和druid監(jiān)控頁面的初始化工作
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)控管理臺的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"); //后臺允許誰可以訪問 //initParams.put("allow", "localhost"):表示只有本機可以訪問 //initParams.put("allow", ""):為空或者為null時,表示允許所有訪問 initParams.put("allow",""); //deny:Druid 后臺拒絕誰訪問 //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:設置哪些請求進行過濾排除掉,從而不進行統(tǒng)計 Map<String, String> initParams = new HashMap<>(); initParams.put("exclusions", "*.js,*.css,/druid/*"); bean.setInitParameters(initParams); //"/*" 表示過濾所有請求 bean.setUrlPatterns(Arrays.asList("/*")); return bean; } }
編寫controller類進行測試(此處使用jdbcTemplate進行演示)
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實現(xiàn)數(shù)據(jù)庫操作 * @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; } }
啟動項目,演示效果
項目啟動日志:
druid的監(jiān)控頁面訪問http://localhost:8080/druid/sql.html
二、druid多數(shù)據(jù)源的配置使用
修改application.yml文件
spring: datasource: local: username: root password: root #注意多數(shù)據(jù)源配置的時候此處為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ù)據(jù)源:
編寫枚舉類,用于指定數(shù)據(jù)源
package com.czing.jdbcdemo.mult; public enum DataSourceType { REMOTE, LOCAL }
數(shù)據(jù)源切換的處理類
package com.czing.jdbcdemo.mult; public class DynamicDataSourceContextHolder { /** * 使用ThreadLocal維護變量,ThreadLocal為每個使用該變量的線程提供獨立的變量副本, * 所以每一個線程都可以獨立地改變自己的副本,而不會影響其它線程所對應的副本。 */ private static final ThreadLocal<String> CONTEXT_HOLDER = new ThreadLocal<>(); /** * 設置數(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ù)源信息加載的實現(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)用時用來將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ù)源的配置啟動類,注入數(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); } }
自定義注解
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攔截類的實現(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測試類的編寫驗證
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實現(xiàn)數(shù)據(jù)庫操作 * @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實現(xiàn)數(shù)據(jù)庫操作 * @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; } }
啟動項目,分別訪問兩個接口查詢不同的數(shù)據(jù)源
http://localhost:8080/selectTest的訪問數(shù)據(jù):
http://localhost:8080/selectRemote的訪問數(shù)據(jù)
結語
以上為springboot實現(xiàn)druid配置查詢的demo,并且演示了如何實現(xiàn)多數(shù)據(jù)源配置動態(tài)切換的代碼實現(xiàn),注意多數(shù)據(jù)源配置的時候url的配置為jdbc-url
到此這篇關于springboot整合druid及多數(shù)據(jù)源配置的文章就介紹到這了,更多相關springboot整合druid內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Spring 實現(xiàn)excel及pdf導出表格示例
本篇文章主要介紹了Spring 實現(xiàn)excel及pdf導出表格示例,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-03-03SpringBoot集成thymeleaf渲染html模板的步驟詳解
這篇文章主要給大家詳細介紹了SpringBoot集成thymeleaf如何使實現(xiàn)html模板的渲染,文中有詳細的代碼示例,具有一定的參考價值,需要的朋友可以參考下2023-06-06