這期內(nèi)容當(dāng)中小編將會給大家?guī)碛嘘P(guān)SpringBoot中怎么實(shí)現(xiàn)一個讀寫分離組件,文章內(nèi)容豐富且以專業(yè)的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。
創(chuàng)新互聯(lián)公司-專業(yè)網(wǎng)站定制、快速模板網(wǎng)站建設(shè)、高性價比余干網(wǎng)站開發(fā)、企業(yè)建站全套包干低至880元,成熟完善的模板庫,直接使用。一站式余干網(wǎng)站制作公司更省心,省錢,快速模板網(wǎng)站建設(shè)找我們,業(yè)務(wù)覆蓋余干地區(qū)。費(fèi)用合理售后完善,10多年實(shí)體公司更值得信賴。
org.springframework.boot spring-boot-starter org.springframework.boot spring-boot-starter-data-jpa org.springframework.boot spring-boot-configuration-processor true
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:定義切點(diǎn),那些方法是需要攔截(從讀庫中操作)。
master:寫庫配置。
slaves:讀庫配置(List集合)。
@Component @ConfigurationProperties(prefix = "pack.datasource") public class RWDataSourceProperties { private String pointcut ; private HikariConfig master ; private Listslaves = 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 ListslaveDataSources(RWDataSourceProperties rwDataSourceProperties) { List 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 slaveDataSources) { BaseRoutingDataSource ds = new BaseRoutingDataSource() ; Map
public class BaseRoutingDataSource extends AbstractRoutingDataSource {
@Resource
private DataSourceHolder holder;
@Override
protected Object determineCurrentLookupKey() {
return holder.get() ;
}
}
public class DataSourceHolder { private ThreadLocalcontext = new ThreadLocal () { @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動態(tài)設(shè)置context的內(nèi)容值,0為從寫庫中操作,其它的都在讀庫中操作。
BaseSlaveLoad類為到底從那個讀庫中選取的一個算法類,默認(rèn)實(shí)現(xiàn)使用的是輪詢算法。
public interface BaseSlaveLoad {
int load() ;
}
public abstract class AbstractSlaveLoad implements BaseSlaveLoad { @Resource protected ListslaveDataSources ; }
這里定義一個抽象類注入了讀庫列表,所有的實(shí)現(xiàn)類從該類中繼承即可。
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(); } }
應(yīng)該切點(diǎn)需要動態(tài)配置,所以這里采用spring aop的方式來配置
@Bean public AspectJExpressionPointcutAdvisor logAdvisor(RWDataSourceProperties props, DataSourceHolder holder) { AspectJExpressionPointcutAdvisor advisor = new AspectJExpressionPointcutAdvisor() ; logger.info("執(zhí)行表達(dá)式:{}", 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的注解方法會類都會從讀庫中操作。
到此讀寫分離組件開發(fā)完成。
mvn install -Dmaven.test.skip=true
引入依賴
com.pack xg-component-rw 1.0.0
啟動類添加注解開啟讀寫分離功能
@SpringBootApplication @EnableRW public class BaseWebApplication { public static void main(String[] args) { SpringApplication.run(BaseWebApplication.class, args); } }
測試:
第一次查詢:
第二次查詢:
為了區(qū)別兩個從庫設(shè)置不同的數(shù)據(jù)
上述就是小編為大家分享的SpringBoot中怎么實(shí)現(xiàn)一個讀寫分離組件了,如果剛好有類似的疑惑,不妨參照上述分析進(jìn)行理解。如果想知道更多相關(guān)知識,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。