摘要: 本篇文章的场景是做调度中心和监控中心时的需求,后端使用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. spring 5.x 系列第19篇 ——spring简单邮件、附件邮件、内嵌资源邮件、模板邮件发送 (xml配置方式)

    源码Gitub地址:https://github.com/heibaiying/spring-samples-for-all 一.说明 1.1 项目结构说明 邮件发送配置文件为springApplic ...

  2. Java学习笔记——String类型转换

    一滴水里观沧海,一粒沙中看世界 ——一带一路欢迎宴致辞 上代码: package cn.stringtoobj; public class TypeConversion { public static ...

  3. Fiddler如何自动修改请求和响应包

    Charles的Map功能可以将某个请求进行重定向,用重定向的内容响应请求的内容.这个功能非常方便.在抓包过程当中,有时候为了调试方便,需要将线上的服务定位到内网.比如我们线上的服务器域名为 api. ...

  4. CentOS java生成文件并赋予权限的问题

    2.检查文件是否允许: file.canExecute(); – return true, file is executable; false is not. file.canWrite(); – r ...

  5. HDU 6019:MG loves gold(暴力set)

    http://acm.hdu.edu.cn/showproblem.php?pid=6019 题意:给出n个颜色的物品,你每次取只能取连续的不同颜色的物品,问最少要取多少次. 思路:从头往后扫,用se ...

  6. SPOJ INTSUB - Interesting Subset(数学)

    http://www.spoj.com/problems/INTSUB/en/ 题意:给定一个集合,该集合由1,2,3....2n组成,n是一个整数.问该集合中有趣子集的数目,答案mod1e9+7. ...

  7. 充气娃娃什么感觉?Python告诉你

    上期为大家介绍了requests库的基本信息以及使用requests库爬取某东的商品页,收到了很多同学的反馈说期待猪哥的更新,猪哥感到非常开心,今天就带大家来玩一把刺激的! 一.需求背景 在实际开发过 ...

  8. WINDOWS 安装ZeroMQ

    zmq看起来很好用,但是安装起来不是一般麻烦.原来以为java绑定会提供jar包直接可使用,但是官网没有提供已经编译好的库文件和jar.多么的不方便啊!最终还是要自己动手编译! 安装java版本的zm ...

  9. 《An Attentive Survey of Attention Models》阅读笔记

    本文是对文献 <An Attentive Survey of Attention Models> 的总结,详细内容请参照原文. 引言 注意力模型现在已经成为神经网络中的一个重要概念,并已经 ...

  10. 基于 Jmeter 的 web 端接口自动化测试平台(转载)

    框架 功能点 批量导入har包生成接口用例 接口用例分组树形展示 用例编辑失焦自动保存 用例编写提供快捷调试模块 支持多类型参数,json+文本两种校验 支持同一个项目中接口参数传递 提供即时任务+每 ...