gpt4 book ai didi

springboot结合mysql主从来实现读写分离的方法示例

转载 作者:qq735679552 更新时间:2022-09-29 22:32:09 25 4
gpt4 key购买 nike

CFSDN坚持开源创造价值,我们致力于搭建一个资源共享平台,让每一个IT人在这里找到属于你的精彩世界.

这篇CFSDN的博客文章springboot结合mysql主从来实现读写分离的方法示例由作者收集整理,如果你对这篇文章有兴趣,记得点赞哟.

1.实现的功能

    基于springboot框架,application.yml配置多个数据源,使用AOP以及AbstractRootingDataSource、ThreadLocal来实现多数据源切换,以实现读写分离。mysql的主从数据库需要进行设置数据之间的同步.

2.代码实现

    application.properties中的配置 。

?
1
2
3
4
5
6
7
8
9
10
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 。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
@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来标识有哪些数据源 。

?
1
2
3
public enum DBTypeEnum {
     MASTER, SLAVE;
}

然后写一个ThreadLocal本地线程的管理类,用于设置当前线程是那一个数据源 。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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方法.

?
1
2
3
4
5
6
7
8
9
public class DynamicDataSource extends AbstractRoutingDataSource {
     private Logger logger = LogManager.getLogger(DynamicDataSource. class );
 
     @Override
     protected Object determineCurrentLookupKey() {
         logger.info( "此时数据源为{}" , DBContextHolder.get());
         return DBContextHolder.get();
     }
}

最后写一个AOP来实现数据源切换 。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
@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方法都使用主库.

可以使用注解如下来进行优化

?
1
2
3
4
5
6
7
8
9
10
@Retention (RetentionPolicy.RUNTIME)
@Target (ElementType.METHOD)
public @interface DataSource {
 
     @AliasFor ( "dataSource" )
     DBTypeEnum value() default DBTypeEnum.MASTER;
 
     DBTypeEnum dataSource() default DBTypeEnum.MASTER;
 
}

使用此注解来放入到service方法上, 。

?
1
@DataSource (DBTypeEnum.SLAVE)

然后AOP方法修改为:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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主从来实现读写分离的方法示例的文章就介绍到这了,更多相关springboot 读写分离内容请搜索我以前的文章或继续浏览下面的相关文章希望大家以后多多支持我! 。

原文链接:https://blog.csdn.net/yancun93/article/details/103958645 。

最后此篇关于springboot结合mysql主从来实现读写分离的方法示例的文章就讲到这里了,如果你想了解更多关于springboot结合mysql主从来实现读写分离的方法示例的内容请搜索CFSDN的文章或继续浏览相关文章,希望大家以后支持我的博客! 。

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com