摘要: 本篇文章的场景是做调度中心和监控中心时的需求,后端使用TDDL实现分表分库,需求:实现关键业务的查询监控,当用Mybatis查询数据时需要从主库切换到备库或者直接连到备库上查询,从而减小主库的压力,在本篇文章中主要记录在Spring Boot中通过自定义注解结合AOP实现直接连接备库查询。

一.通过AOP 自定义注解实现主库到备库的切换

1.1 自定义注解

自定义注解如下代码所示

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface SwitchDataBase {
boolean switch2Backup() default false;
}

1.2 实现方法拦截器对自定义注解处理

import java.lang.reflect.Method;
import java.util.Arrays; import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component; /**
* 处理走备库逻辑的注解
*/
@Component
public class SwitchDataBaseInterceptor implements MethodInterceptor { private final Logger log = LoggerFactory.getLogger(SwitchDataBaseInterceptor.class); @Override
public Object invoke(MethodInvocation invocation) throws Throwable {
Method method = invocation.getMethod();
SwitchDataBase annotation = getAnnotation(method);
if (annotation == null) {
return invocation.proceed();
}
Object val = null;
if(!ThreadLocalMap.containsKey(GroupDataSourceRouteHelper.DATASOURCE_INDEX)) {
if (annotation.switch2Backup()) {
log.info("query back up DB, method: " + method.getName());
GroupDataSourceRouteHelper.executeByGroupDataSourceIndex(1, true);
} else {
log.info("query primary DB, method: " + method.getName());
GroupDataSourceRouteHelper.executeByGroupDataSourceIndex(0, true);
}
}
try {
val = invocation.proceed();
} catch (Exception e) {
log.info(method.getDeclaringClass().getName() + "." +
invocation.getMethod().getName() + "方法调用失败,arguments:" +
Arrays.toString(invocation.getArguments()));
throw new RuntimeException(e);
} finally {
GroupDataSourceRouteHelper.removeGroupDataSourceIndex();
} return val;
} /**
* 找方法上面声明的注解
*/
private SwitchDataBase getAnnotation(Method method) {
if (method.isAnnotationPresent(SwitchDataBase.class)) {
return method.getAnnotation(SwitchDataBase.class);
}
return null;
} }

1.3 配置OverallQueryConfiguration

在Spring Boot中装配AOP Bean,实现扫描特定目录下的注解,实现切面变成形成通知处理。示例代码如下

import com.wdk.wms.annotation.SwitchDataBaseInterceptor;
import org.springframework.aop.Advisor;
import org.springframework.aop.support.DefaultPointcutAdvisor;
import org.springframework.aop.support.JdkRegexpMethodPointcut;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; @Configuration
public class SwitchDataBaseConfiguration { @Bean(name = "overallQueryInterceptor")
public SwitchDataBaseInterceptor overallQueryInterceptor() {
return new SwitchDataBaseInterceptor();
} //添加aop的pointcut
@Bean(name = "jdkRegexpMethodPointcut")
public JdkRegexpMethodPointcut jdkRegexpMethodPointcut() {
JdkRegexpMethodPointcut jdkRegexpMethodPointcut = new JdkRegexpMethodPointcut();
jdkRegexpMethodPointcut.setPatterns("com.wdk.wms.mapper.*");
return jdkRegexpMethodPointcut;
} //设置默认的aop配置对应的是原来的<aop:advisor>
@Bean
public Advisor druidAdvisor() {
DefaultPointcutAdvisor defaultPointcutAdvisor = new DefaultPointcutAdvisor();
defaultPointcutAdvisor.setPointcut(jdkRegexpMethodPointcut());
defaultPointcutAdvisor.setAdvice(overallQueryInterceptor());
return defaultPointcutAdvisor;
} }

1.4 如何使用注解从主库到备库的切换

@SwitchDataBase(switch2Backup = true)
List<ConsumerNoticeMsg> listByTemplateOver3(@Param("templates") List<Integer> templates);

Spring Boot中自定义注解+AOP实现主备库切换的更多相关文章

  1. Spring Boot2 系列教程(十八)Spring Boot 中自定义 SpringMVC 配置

    用过 Spring Boot 的小伙伴都知道,我们只需要在项目中引入 spring-boot-starter-web 依赖,SpringMVC 的一整套东西就会自动给我们配置好,但是,真实的项目环境比 ...

  2. spring boot 中@Autowired注解无法自动注入的错误

    版权声明:本文为博主原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明. 本文链接:https://blog.csdn.net/huihuilovei/article/de ...

  3. Spring Boot中@Scheduled注解的使用方法

    Spring Boot中@Scheduled注解的使用方法 一.定时任务注解为@Scheduled,使用方式举例如下 //定义一个按时间执行的定时任务,在每天16:00执行一次. @Scheduled ...

  4. 云计算之路-阿里云上:RDS数据库连接数过万引发故障,主备库切换后恢复正常

    非常抱歉!今天 12:03-12:52 ,由于数据库连接数异常突增超过1万,达到了阿里云RDS的最大连接数限制,影响了全站的正常访问.由此给您带来麻烦,请您谅解. 在发现数据库连接数突增的问题后,我们 ...

  5. [terry笔记]11gR2_dataguard_主备库切换

    主备库切换  Switchover  一般SWITCHOVER切换都是计划中的切换,特点是在切换后,不会丢失任何的数据,而且这个过程是可逆的,整个DATA GUARD环境不会被破坏,原来DATA GU ...

  6. 物理DG主备库切换时遇到ORA-16139: media recovery required错误

    在物理DG主备库切换时遇到ORA-16139: media recovery required错误 SQL> ALTER DATABASE COMMIT TO SWITCHOVER TO PRI ...

  7. Spring Boot中的注解

    文章来源:http://www.tuicool.com/articles/bQnMra 在Spring Boot中几乎可以完全弃用xml配置文件,本文的主题是分析常用的注解. Spring最开始是为了 ...

  8. Spring Boot 中自定义 SpringMVC 配置,到底继承谁哪一个类或则接口?

    看了这篇文章,写的非常的言简意赅,特此记录下: 1.Spring Boot 1.x 中,自定义 SpringMVC 配置可以通过继承 WebMvcConfigurerAdapter 来实现. 2.Sp ...

  9. MySQL主备库切换(MHA)演练与总结

      演练包括被动切换和主动切换两部分.被动切换是主库宕机,主动切换是人工手动触发.   演练步骤大致如下:       1 先停掉主库,模拟主库宕机     2 mha将vip切到备库,备库变成主库, ...

随机推荐

  1. springboot 2.X 在访问静态资源的的时候出现404的问题

    通过idea快速搭建一个springboot项目: springboot版本2.1.6 在网上看的资料,springboot静态资源访问如下: "classpath:/META‐INF/re ...

  2. 老雷socket编程之PHP利用socket扩展实现聊天服务

    老雷socket编程之PHP利用socket扩展实现聊天服务 socket聊天服务原理 PHP有两个socket的扩展 sockets和streamssockets socket_create(AF_ ...

  3. PATB 1018. 锤子剪刀布

    时间限制 100 ms 内存限制 65536 kB 代码长度限制 8000 B 判题程序 Standard 作者 CHEN, Yue 大家应该都会玩“锤子剪刀布”的游戏:两人同时给出手势,胜负规则如图 ...

  4. Redis 学习笔记(篇四):整数集合和压缩列表

    整数集合 Redis 中当一个集合(set)中只包含整数,并且元素不多时,底层使用整数集合实现,否则使用字典实现. 那么: 为什么会出现整数集合呢?都使用字典存储不行吗? 整数集合在 Redis 中的 ...

  5. Python连载21-collections模块

    一.collections模块 1.函数namedtuple (1)作用:tuple类型,是一个可命名的tuple (2)格式:collections(列表名称,列表) (3)​返回值:一个含有列表的 ...

  6. 常用的方法论-SWOT

  7. 常用的方法论-PARR

  8. POJ 3686:The Windy's(最小费用最大流)***

    http://poj.org/problem?id=3686 题意:给出n个玩具和m个工厂,每个工厂加工每个玩具有一个时间,问要加工完这n个玩具最少需要等待的平均时间.例如加工1号玩具时间为t1,加工 ...

  9. php中对象类型与数组之间的转换

    1.刚看视频学习的时候看到一个困扰很久的问题, 有时候我们在进行做项目的时候会碰到的一个小问题.举一个小例子.  获取一个xml文件里面的数据. xml.xml文件如下: <?xml versi ...

  10. H5学习笔记-应用缓存,Web worker,服务器发送事件

    ↑亮了 应用缓存用法 <!DOCTYPE HTML> <html manifest="demo.appcache"> <body> The co ...