您好,登錄后才能下訂單哦!
這篇文章主要介紹springboot結合mysql主從來實現讀寫分離的方法,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!
基于springboot框架,application.yml配置多個數據源,使用AOP以及AbstractRootingDataSource、ThreadLocal來實現多數據源切換,以實現讀寫分離。mysql的主從數據庫需要進行設置數據之間的同步。
application.properties中的配置
spring.datasource.druid.master.driver-class-name=com.mysql.jdbc.Driver spring.datasource.druid.master.url=jdbc:mysql://127.0.0.1:3306/node2?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&autoReconnect=true&useSSL=false spring.datasource.druid.master.username=root spring.datasource.druid.master.password=123456 spring.datasource.druid.slave.driver-class-name=com.mysql.jdbc.Driver spring.datasource.druid.slave.url=jdbc:mysql://127.0.0.1:3306/node1?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&autoReconnect=true&useSSL=false spring.datasource.druid.slave.username=root spring.datasource.druid.slave.password=123456
寫一個DataSourceConfig.java來注入兩個bean
@Bean @ConfigurationProperties("spring.datasource.druid.master") public DataSource masterDataSource() { logger.info("select master data source"); return DruidDataSourceBuilder.create().build(); } @Bean @ConfigurationProperties("spring.datasource.druid.slave") public DataSource slaveDataSource() { logger.info("select slave data source"); return DruidDataSourceBuilder.create().build(); }
寫一個enum來標識有哪些數據源
public enum DBTypeEnum { MASTER, SLAVE; }
然后寫一個ThreadLocal本地線程的管理類,用于設置當前線程是那一個數據源
private static final ThreadLocal<DBTypeEnum> contextHolder = new ThreadLocal<>(); private static final ThreadLocal<DBTypeEnum> contextHolder2 = ThreadLocal.withInitial(() -> DBTypeEnum.MASTER); public static void set(DBTypeEnum dbType) { contextHolder.set(dbType); } public static DBTypeEnum get() { return contextHolder.get(); } public static void master() { set(DBTypeEnum.MASTER); logger.info("切換到master數據源"); } public static void slave() { set(DBTypeEnum.SLAVE); logger.info("切換到slave數據源"); } public static void cleanAll() { contextHolder.remove(); }
然后寫一個DynamicDataSource繼承AbstractRootingDataSource,重寫它的determineCurrentLookupKey方法。
public class DynamicDataSource extends AbstractRoutingDataSource { private Logger logger = LogManager.getLogger(DynamicDataSource.class); @Override protected Object determineCurrentLookupKey() { logger.info("此時數據源為{}", DBContextHolder.get()); return DBContextHolder.get(); } }
最后寫一個AOP來實現數據源切換
@Aspect @Order(1) @Component public class DataSourceAop { private Logger logger = LogManager.getLogger(DataSourceAop.class); @Pointcut("(execution(* com.springboot.demo.service..*.select*(..)) " + "|| execution(* com.springboot.demo.service..*.find*(..)) " + "|| execution(* com.springboot.demo.service..*.get*(..)))") public void readPointcut() { logger.info("read only operate ,into slave db"); } @Pointcut("execution(* com.springboot.demo.service..*.insert*(..)) " + "|| execution(* com.springboot.demo.service..*.update*(..)) " + "|| execution(* com.springboot.demo.service..*.delete*(..)) ") public void writePointcut() { logger.info("read or write operate ,into master db"); } @Before("readPointcut()") public void read() { logger.info("read operate"); DBContextHolder.slave(); } @Before("writePointcut()") public void write() { logger.info("write operate"); DBContextHolder.master(); } @After("writePointcut(),readPointcut()") public void clean() { logger.info("dataSource cleanAll"); DBContextHolder.cleanAll(); } }
注意:這里只是使用了偷懶的方法,對于service里面的select、get、find前綴的方法都使用從庫,對于insert、update和delete方法都使用主庫。
可以使用注解如下來進行優化:
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface DataSource { @AliasFor("dataSource") DBTypeEnum value() default DBTypeEnum.MASTER; DBTypeEnum dataSource() default DBTypeEnum.MASTER; }
使用此注解來放入到service方法上,
@DataSource(DBTypeEnum.SLAVE)
然后AOP方法修改為:
private static final String POINT = "execution (* com.springboot.demo.service.*.*(..))"; @Around(POINT) public Object dataSourceAround(ProceedingJoinPoint joinPoint) throws Throwable { Object[] args = joinPoint.getArgs(); Object obj; Object target = joinPoint.getTarget(); String methodName = joinPoint.getSignature().getName(); Class clazz = target.getClass(); Class<?>[] parameterTypes = ((MethodSignature) joinPoint.getSignature()).getMethod().getParameterTypes(); boolean isDynamicDataSourceMethod = false; try { Method method = clazz.getMethod(methodName, parameterTypes); DataSources currentDataSource = null; if (method != null && method.isAnnotationPresent(DataSource.class)) { isDynamicDataSourceMethod = true; currentDataSource = method.getAnnotation(DataSource.class).value(); DataSourceTypeManager.set(currentDataSource); log.info("DataSourceInterceptor Switch DataSource To {}",currentDataSource); } obj = joinPoint.proceed(args); if (isDynamicDataSourceMethod) { log.info("DataSourceInterceptor DataSource {} proceed",currentDataSource); } } finally { if (isDynamicDataSourceMethod) { DataSourceTypeManager.reset(); log.info("DataSourceInterceptor Reset DataSource To {}",DataSourceTypeManager.get()); } } return obj; }
以上是“springboot結合mysql主從來實現讀寫分離的方法”這篇文章的所有內容,感謝各位的閱讀!希望分享的內容對大家有幫助,更多相關知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。