spring boot多數(shù)據(jù)源動(dòng)態(tài)切換代碼實(shí)例
這篇文章主要介紹了spring boot多數(shù)據(jù)源動(dòng)態(tài)切換代碼實(shí)例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
當(dāng)項(xiàng)目中存在多數(shù)據(jù)源時(shí),就涉及到數(shù)據(jù)源的動(dòng)態(tài)切換,通過研究,特此記錄一下。
1、maven依賴
<!--數(shù)據(jù)庫連接--> <dependency> <groupId>com.oracle</groupId> <artifactId>ojdbc6</artifactId> <version>11.2.0.4</version> <scope>runtime</scope> </dependency> <!--數(shù)據(jù)庫連接池-> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.1.10</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <!--aop-> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency>
2、多數(shù)據(jù)源信息配置
#多數(shù)據(jù)源測試 spring: datasource: druid: master: driver-class-name: oracle.jdbc.driver.OracleDriver username: test password: test url: jdbc:oracle:thin:@//ip1:1521/orcl slave: driver-class-name: oracle.jdbc.driver.OracleDriver username: test password: test url: jdbc:oracle:thin:@//ip2:1521/orcl
3、數(shù)據(jù)源配置信息轉(zhuǎn)換成實(shí)體類
@ConfigurationProperties(prefix = "spring.datasource.druid") @Data @Component public class DataSourceProperties { private Map<String,String>master; private Map<String,String>slave; }
4、動(dòng)態(tài)數(shù)據(jù)源切換類
public class DynamicDataSource extends AbstractRoutingDataSource { private static final ThreadLocal<String> contextHolder = new ThreadLocal<>(); public DynamicDataSource(DataSource defaultTargetDataSource, Map<Object, Object> targetDataSources) { super.setDefaultTargetDataSource(defaultTargetDataSource); super.setTargetDataSources(targetDataSources); super.afterPropertiesSet(); } @Override protected Object determineCurrentLookupKey() { return getDataSource(); } public static void setDataSource(String dataSource) { contextHolder.set(dataSource); } public static String getDataSource() { return contextHolder.get(); } public static void clearDataSource() { contextHolder.remove(); } }
5、多數(shù)據(jù)源配置類
@Configuration public class DynamicDataSourceConfig { @Bean public DataSource master(@Autowired DataSourceProperties dataSourceProperties){ DruidDataSource druidDataSource = new DruidDataSource(); Map<String, String> master = dataSourceProperties.getMaster(); druidDataSource.setUsername(master.get("username")); druidDataSource.setPassword(master.get("password")); druidDataSource.setUrl(master.get("url")); //其他參數(shù)配置 省略 return druidDataSource; } @Bean public DataSource slave(@Autowired DataSourceProperties dataSourceProperties){ DruidDataSource druidDataSource = new DruidDataSource(); Map<String, String> slave = dataSourceProperties.getSlave(); druidDataSource.setUsername(slave.get("username")); druidDataSource.setPassword(slave.get("password")); druidDataSource.setUrl(slave.get("url")); //其他參數(shù)配置 省略 return druidDataSource; } @Bean @Primary public DynamicDataSource dataSource(DataSource master,DataSource slave){ Map<Object,Object>map = new HashMap<>(4); map.put("master",master); map.put("slave",slave); return new DynamicDataSource(master,map); } }
6、自定義@DataSource注解
@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface DataSource { String name() default "master"; }
7、Aop切面類配置
@Component @Aspect public class DataSourceAspect { @Pointcut("@annotation(com.zxgeo.sso.muiltDatasource.anons.DataSource)") public void dataSourcePointCut(){} @Around(value = "dataSourcePointCut()") 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){ DynamicDataSource.setDataSource("master"); }else { DynamicDataSource.setDataSource(dataSource.name()); } try { return point.proceed(); } finally { DynamicDataSource.clearDataSource(); } } }
8、啟動(dòng)配置注解信息,重要(不然運(yùn)行會(huì)報(bào)錯(cuò))
@SpringBootApplication(exclude= {DataSourceAutoConfiguration.class})
9、測試
(1)、service層(此處沒有使用mybatis)
@Service public class TestService { @Autowired private javax.sql.DataSource dataSource; @DataSource public Map<String,Object> getMasterDataSource() throws SQLException { Connection connection = dataSource.getConnection(); Map<String,Object> map; try (PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM AA WHERE A=10001")) { ResultSet resultSet = preparedStatement.executeQuery(); map = new HashMap<>(); while (resultSet.next()){ map.put("A",resultSet.getString("A")); map.put("B",resultSet.getString("B")); map.put("C",resultSet.getString("C")); } } return map; } @DataSource(name = "slave") public Map<String,Object> getSlaveDataSource() throws SQLException { Connection connection = dataSource.getConnection(); Map<String,Object> map; try (PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM AA WHERE A=10002")) { ResultSet resultSet = preparedStatement.executeQuery(); map = new HashMap<>(); while (resultSet.next()){ map.put("A",resultSet.getString("A")); map.put("B",resultSet.getString("B")); map.put("C",resultSet.getString("C")); } } return map; } }
(2)、單元測試
@SpringBootTest @RunWith(SpringRunner.class) class SsoApplicationTests { @Autowired private TestService testService; @Test public void muliDatasorce() throws SQLException { Map<String, Object> masterDataSourceUrl = testService.getMasterDataSource(); System.out.println(masterDataSourceUrl); Map<String, Object> slaveDataSourceUrl = testService.getSlaveDataSource(); System.out.println(slaveDataSourceUrl); } }
(3)、結(jié)果:
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Java使用poi實(shí)現(xiàn)excel的導(dǎo)入操作指南
使用Apache Poi是一種流行且廣泛使用的方式,可以幫助開發(fā)人員直接從Java代碼中讀取、寫入和處理Excel文件,因此在這篇文章我們將著重介紹如何實(shí)現(xiàn)excel的導(dǎo)入,感興趣的朋友可以跟著小編一起來學(xué)習(xí)2023-06-06JVM內(nèi)存區(qū)域劃分相關(guān)原理詳解
這篇文章主要介紹了JVM內(nèi)存區(qū)域劃分相關(guān)原理詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-10-10深入學(xué)習(xí)java ThreadLocal的源碼知識(shí)
ThreadLocal是一個(gè)本地線程副本變量工具類。主要用于將私有線程和該線程存放的副本對象做一個(gè)映射,各個(gè)線程之間的變量互不干擾,特別適用于各個(gè)線程依賴不通的變量值完成操作的場景。下面我們來詳細(xì)了解一下它吧2019-06-06SpringBoot高并發(fā)下控制限流的幾種實(shí)現(xiàn)方法
隨著業(yè)務(wù)的發(fā)展,高并發(fā)成為很多系統(tǒng)不得不面對的問題,限流作為一種常用的技術(shù)手段,可以幫助我們有效地控制請求的流量,避免系統(tǒng)因過載而崩潰,本文將介紹在Spring Boot應(yīng)用中實(shí)現(xiàn)限流的幾種方法,需要的朋友可以參考下2024-06-06Java SpringBoot實(shí)現(xiàn)AOP
AOP包括連接點(diǎn)(JoinPoint)、切入點(diǎn)(Pointcut)、增強(qiáng)(Advisor)、切面(Aspect)、AOP代理(AOP Proxy),具體的方法和類型下面文章會(huì)舉例說明,感興趣的小伙伴和小編一起閱讀全文吧2021-09-09Java基于TCP協(xié)議socket網(wǎng)絡(luò)編程的文件傳送的實(shí)現(xiàn)
這篇文章主要介紹了Java基于TCP協(xié)議socket網(wǎng)絡(luò)編程的文件傳送的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-12-12