springboot -- druid 多資料來源(註解版)
阿新 • • 發佈:2018-12-04
1.通過註解實現不同的資料庫彼此切換。
2.pom依賴:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
3.自定義註解
package com.example.jdbc.demo.config; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface TargetDataSource { DataSourceKey dataSourceKey() default DataSourceKey.ZHWDEMO; }
3.配置資料來源
public class DynamicDataSource extends AbstractRoutingDataSource {
。。。。。。。
//必須實現其方法
protected Object determineCurrentLookupKey() {
return DataSourceContextHolder.getDBType();
}
}
4.資料庫列舉
public enum DataSourceKey { /** * Master data source key. */ ZHWDEMO, /** * Slave alpha data source key. */ WSS }
注意:只能控制當前資料來源的事務,不能控制其他資料來源的事務,如果需要的化需要你去了解分散式事務控制方式。