您好,登錄后才能下訂單哦!
這篇文章主要介紹“SpringBoot中如何實現一個讀寫分離組件”的相關知識,小編通過實際案例向大家展示操作過程,操作方法簡單快捷,實用性強,希望這篇“SpringBoot中如何實現一個讀寫分離組件”文章能幫助大家解決問題。
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency>
pack: datasource: pointcut: execution(public * net.greatsoft.service.base.*.*(..)) || execution(public * net.greatsoft.service.xxx.*.*(..)) master: driverClassName: oracle.jdbc.driver.OracleDriver jdbcUrl: jdbc:oracle:thin:@10.100.102.113:1521/orcl username: test password: test minimumIdle: 10 maximumPoolSize: 200 autoCommit: true idleTimeout: 30000 poolName: MbookHikariCP maxLifetime: 1800000 connectionTimeout: 30000 connectionTestQuery: SELECT 1 FROM DUAL slaves: - driverClassName: oracle.jdbc.driver.OracleDriver jdbcUrl: jdbc:oracle:thin:@10.100.102.113:1521/orcl username: dc password: dc minimumIdle: 10 maximumPoolSize: 200 autoCommit: true idleTimeout: 30000 poolName: MbookHikariCP maxLifetime: 1800000 connectionTimeout: 30000 connectionTestQuery: SELECT 1 FROM DUAL - driverClassName: oracle.jdbc.driver.OracleDriver jdbcUrl: jdbc:oracle:thin:@10.100.102.113:1521/orcl username: empi password: empi minimumIdle: 10 maximumPoolSize: 200 autoCommit: true idleTimeout: 30000 poolName: MbookHikariCP maxLifetime: 1800000 connectionTimeout: 30000 connectionTestQuery: SELECT 1 FROM DUAL
pointcut:定義切點,那些方法是需要攔截(從讀庫中操作)。
master:寫庫配置。
slaves:讀庫配置(List集合)。
@Component @ConfigurationProperties(prefix = "pack.datasource") public class RWDataSourceProperties { private String pointcut ; private HikariConfig master ; private List<HikariConfig> slaves = new ArrayList<>(); }
public class RWConfig { private static Logger logger = LoggerFactory.getLogger(RWConfig.class) ; @Bean public HikariDataSource masterDataSource(RWDataSourceProperties rwDataSourceProperties) { return new HikariDataSource(rwDataSourceProperties.getMaster()) ; } @Bean public List<HikariDataSource> slaveDataSources(RWDataSourceProperties rwDataSourceProperties) { List<HikariDataSource> lists = new ArrayList<>() ; for(HikariConfig config : rwDataSourceProperties.getSlaves()) { lists.add(new HikariDataSource(config)) ; } return lists ; } @Bean @Primary @DependsOn({"masterDataSource", "slaveDataSources"}) public AbstractRoutingDataSource routingDataSource(@Qualifier("masterDataSource")DataSource masterDataSource, @Qualifier("slaveDataSources")List<HikariDataSource> slaveDataSources) { BaseRoutingDataSource ds = new BaseRoutingDataSource() ; Map<Object, Object> targetDataSources = new HashMap<>(2) ; targetDataSources.put("master", masterDataSource) ; for (int i = 0; i < slaveDataSources.size(); i++) { targetDataSources.put("slave-" + i, slaveDataSources.get(i)) ; } ds.setDefaultTargetDataSource(masterDataSource) ; ds.setTargetDataSources(targetDataSources) ; return ds ; } }
public class BaseRoutingDataSource extends AbstractRoutingDataSource {
@Resource
private DataSourceHolder holder;
@Override
protected Object determineCurrentLookupKey() {
return holder.get() ;
}
}
public class DataSourceHolder { private ThreadLocal<Integer> context = new ThreadLocal<Integer>() { @Override protected Integer initialValue() { return 0 ; } }; @Resource private BaseSlaveLoad slaveLoad ; public String get() { Integer type = context.get() ; return type == null || type == 0 ? "master" : "slave-" + slaveLoad.load() ; } public void set(Integer type) { context.set(type) ; } }
通過aop動態設置context的內容值,0為從寫庫中操作,其它的都在讀庫中操作。
BaseSlaveLoad類為到底從那個讀庫中選取的一個算法類,默認實現使用的是輪詢算法。
public interface BaseSlaveLoad {
int load() ;
}
public abstract class AbstractSlaveLoad implements BaseSlaveLoad { @Resource protected List<HikariDataSource> slaveDataSources ; }
這里定義一個抽象類注入了讀庫列表,所有的實現類從該類中繼承即可。
public class PollingLoad extends AbstractSlaveLoad { private int index = 0 ; private int size = 1 ; @PostConstruct public void init() { size = slaveDataSources.size() ; } @Override public int load() { int n = index ; synchronized (this) { index = (++index) % size ; } return n ; } }
配置成Bean
@Bean @ConditionalOnMissingBean public BaseSlaveLoad slaveLoad() { return new PollingLoad() ; } @Bean public DataSourceHolder dataSourceHolder() { return new DataSourceHolder() ; }
public class DataSourceAspect implements MethodInterceptor { private DataSourceHolder holder ; public DataSourceAspect(DataSourceHolder holder) { this.holder = holder ; } @Override public Object invoke(MethodInvocation invocation) throws Throwable { Method method = invocation.getMethod() ; String methodName = method.getName() ; SlaveDB slaveDB = method.getAnnotation(SlaveDB.class) ; if (slaveDB == null) { slaveDB = method.getDeclaringClass().getAnnotation(SlaveDB.class) ; } if (methodName.startsWith("find") || methodName.startsWith("get") || methodName.startsWith("query") || methodName.startsWith("select") || methodName.startsWith("list") || slaveDB != null) { holder.set(1) ; } else { holder.set(0) ; } return invocation.proceed(); } }
應該切點需要動態配置,所以這里采用spring aop的方式來配置
@Bean public AspectJExpressionPointcutAdvisor logAdvisor(RWDataSourceProperties props, DataSourceHolder holder) { AspectJExpressionPointcutAdvisor advisor = new AspectJExpressionPointcutAdvisor() ; logger.info("執行表達式:{}", props.getPointcut()) ; advisor.setExpression(props.getPointcut()) ; advisor.setAdvice(new DataSourceAspect(holder)) ; return advisor ; }
public class RWImportSelector implements ImportSelector { @Override public String[] selectImports(AnnotationMetadata importingClassMetadata) { return new String[] {RWConfig.class.getName()} ; } }
這里的RWConfig為我們上面的配置類
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Import({RWImportSelector.class})
public @interface EnableRW {
}
@Documented @Retention(RUNTIME) @Target({ TYPE, METHOD }) public @interface SlaveDB { }
有@SlaveDB的注解方法會類都會從讀庫中操作。
到此讀寫分離組件開發完成。
mvn install -Dmaven.test.skip=true
引入依賴
<dependency> <groupId>com.pack</groupId> <artifactId>xg-component-rw</artifactId> <version>1.0.0</version> </dependency>
啟動類添加注解開啟讀寫分離功能
@SpringBootApplication @EnableRW public class BaseWebApplication { public static void main(String[] args) { SpringApplication.run(BaseWebApplication.class, args); } }
測試:
第一次查詢:
第二次查詢:
為了區別兩個從庫設置不同的數據
關于“SpringBoot中如何實現一個讀寫分離組件”的內容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業相關的知識,可以關注億速云行業資訊頻道,小編每天都會為大家更新不同的知識點。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。