经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » Java相关 » Spring » 查看文章
SpringBoot + 自定义注解 + AOP 高级玩法打造通用开关
来源:cnblogs  作者:程序员济癫  时间:2023/10/17 11:02:12  对本文有异议

前言

最近在工作中迁移代码的时候发现了以前自己写的一个通用开关实现,发现挺不错,特地拿出来分享给大家。

为了有良好的演示效果,我特地重新建了一个项目,把核心代码提炼出来加上了更多注释说明,希望xdm喜欢。

案例

1、项目结构

image

2、引入依赖

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-web</artifactId>
  4. </dependency>
  5. <dependency>
  6. <groupId>org.springframework.boot</groupId>
  7. <artifactId>spring-boot-starter-aop</artifactId>
  8. </dependency>
  9. <dependency>
  10. <groupId>org.springframework.boot</groupId>
  11. <artifactId>spring-boot-starter-data-redis</artifactId>
  12. </dependency>
  13. <dependency>
  14. <groupId>org.projectlombok</groupId>
  15. <artifactId>lombok</artifactId>
  16. <optional>true</optional>
  17. </dependency>

3、yml配置

连接Redis的配置修改成自己的

  1. server:
  2. port: 8888
  3. spring:
  4. redis:
  5. database: 6
  6. host: xx.xx.xx.xx
  7. port: 6379
  8. password: 123456
  9. jedis:
  10. pool:
  11. max-active: 100
  12. max-wait: -1ms
  13. max-idle: 50
  14. min-idle: 1

4、自定义注解

这里稍微说明下,定义了一个key对应不同功效的开关,定义了一个val作为开关是否打开的标识,以及一个message作为消息提示。

  1. package com.example.commonswitch.annotation;
  2. import com.example.commonswitch.constant.Constant;
  3. import java.lang.annotation.ElementType;
  4. import java.lang.annotation.Retention;
  5. import java.lang.annotation.RetentionPolicy;
  6. import java.lang.annotation.Target;
  7. /**
  8. * <p>
  9. * 通用开关注解
  10. * </p>
  11. *
  12. * @author 程序员济癫
  13. * @since 2023-10-16 17:38
  14. */
  15. @Target({ElementType.METHOD}) // 作用在方法上
  16. @Retention(RetentionPolicy.RUNTIME) // 运行时起作用
  17. public @interface ServiceSwitch {
  18. /**
  19. * 业务开关的key(不同key代表不同功效的开关)
  20. * {@link Constant.ConfigCode}
  21. */
  22. String switchKey();
  23. // 开关,0:关(拒绝服务并给出提示),1:开(放行)
  24. String switchVal() default "0";
  25. // 提示信息,默认值可在使用注解时自行定义。
  26. String message() default "当前请求人数过多,请稍后重试。";
  27. }

5、定义常量

主要用来存放各种开关的key

  1. package com.example.commonswitch.constant;
  2. /**
  3. * <p>
  4. * 常量类
  5. * </p>
  6. *
  7. * @author 程序员济癫
  8. * @since 2023-10-16 17:45
  9. */
  10. public class Constant {
  11. // .... 其他业务相关的常量 ....
  12. // 配置相关的常量
  13. public static class ConfigCode {
  14. // 挂号支付开关(0:关,1:开)
  15. public static final String REG_PAY_SWITCH = "reg_pay_switch";
  16. // 门诊支付开关(0:关,1:开)
  17. public static final String CLINIC_PAY_SWITCH = "clinic_pay_switch";
  18. // 其他业务相关的配置常量
  19. // ....
  20. }
  21. }

6、AOP核心实现

核心实现中我专门加了详细的注释说明,保证大家一看就懂,而且把查询开关的方式列举出来供大家自己选择。

  1. package com.example.commonswitch.aop;
  2. import com.example.commonswitch.annotation.ServiceSwitch;
  3. import com.example.commonswitch.constant.Constant;
  4. import com.example.commonswitch.exception.BusinessException;
  5. import com.example.commonswitch.util.Result;
  6. import lombok.AllArgsConstructor;
  7. import lombok.extern.slf4j.Slf4j;
  8. import org.aspectj.lang.ProceedingJoinPoint;
  9. import org.aspectj.lang.annotation.Around;
  10. import org.aspectj.lang.annotation.Aspect;
  11. import org.aspectj.lang.annotation.Pointcut;
  12. import org.aspectj.lang.reflect.MethodSignature;
  13. import org.springframework.data.redis.core.StringRedisTemplate;
  14. import org.springframework.http.HttpStatus;
  15. import org.springframework.stereotype.Component;
  16. import java.lang.reflect.Method;
  17. /**
  18. * <p>
  19. * 开关实现的切面类
  20. * </p>
  21. *
  22. * @author 程序员济癫
  23. * @since 2023-10-16 17:56
  24. */
  25. @Aspect
  26. @Component
  27. @Slf4j
  28. @AllArgsConstructor
  29. public class ServiceSwitchAOP {
  30. private final StringRedisTemplate redisTemplate;
  31. /**
  32. * 定义切点,使用了@ServiceSwitch注解的类或方法都拦截
  33. */
  34. @Pointcut("@annotation(com.example.commonswitch.annotation.ServiceSwitch)")
  35. public void pointcut() {
  36. }
  37. @Around("pointcut()")
  38. public Object around(ProceedingJoinPoint point) {
  39. // 获取被代理的方法的参数
  40. Object[] args = point.getArgs();
  41. // 获取被代理的对象
  42. Object target = point.getTarget();
  43. // 获取通知签名
  44. MethodSignature signature = (MethodSignature) point.getSignature();
  45. try {
  46. // 获取被代理的方法
  47. Method method = target.getClass().getMethod(signature.getName(), signature.getParameterTypes());
  48. // 获取方法上的注解
  49. ServiceSwitch annotation = method.getAnnotation(ServiceSwitch.class);
  50. // 核心业务逻辑
  51. if (annotation != null) {
  52. String switchKey = annotation.switchKey();
  53. String switchVal = annotation.switchVal();
  54. String message = annotation.message();
  55. /*
  56. 获取配置项说明
  57. 这里有两种方式:1、配置加在Redis,查询时从Redis获取;
  58. 2、配置加在数据库,查询时从表获取。(MySQL单表查询其实很快,配置表其实也没多少数据)
  59. 我在工作中的做法:直接放到数据库,但是获取配置项的方法用SpringCache缓存,
  60. 然后在后台管理中操作配置项,变更时清理缓存即可。
  61. 我这么做就是结合了上面两种各自的优点,因为项目中配置一般都是用后台管理来操作的,
  62. 查表当然更舒适,同时加上缓存提高查询性能。
  63. */
  64. // 下面这块查询配置项,大家可以自行接入并修改。
  65. // 数据库这么查询:String configVal = systemConfigService.getConfigByKey(switchKey);
  66. // 这里我直接从redis中取,使用中大家可以按照意愿自行修改。
  67. String configVal = redisTemplate.opsForValue().get(Constant.ConfigCode.REG_PAY_SWITCH);
  68. if (switchVal.equals(configVal)) {
  69. // 开关打开,则返回提示。
  70. return new Result<>(HttpStatus.FORBIDDEN.value(), message);
  71. }
  72. }
  73. // 放行
  74. return point.proceed(args);
  75. } catch (Throwable e) {
  76. throw new BusinessException(e.getMessage(), e);
  77. }
  78. }
  79. }

7、使用注解

我们定义一个服务来使用这个开关,我设定了一个场景是挂号下单,也就是把开关用在支付业务这里。

因为支付场景在线上有可能出现未知问题,比如第三方rpc调用超时或不响应,或者对方业务出现缺陷,导致我方不断出现长款,那么我们此时立马操作后台将支付开关关掉,能最大程度止损。

  1. package com.example.commonswitch.service;
  2. import com.example.commonswitch.annotation.ServiceSwitch;
  3. import com.example.commonswitch.constant.Constant;
  4. import com.example.commonswitch.util.Result;
  5. import org.springframework.http.HttpStatus;
  6. import org.springframework.stereotype.Service;
  7. /**
  8. * <p>
  9. * 挂号服务
  10. * </p>
  11. *
  12. * @author 程序员济癫
  13. * @since 2023-10-16 18:48
  14. */
  15. @Service
  16. public class RegService {
  17. /**
  18. * 挂号下单
  19. */
  20. @ServiceSwitch(switchKey = Constant.ConfigCode.REG_PAY_SWITCH)
  21. public Result createOrder() {
  22. // 具体下单业务逻辑省略....
  23. return new Result(HttpStatus.OK.value(), "挂号下单成功");
  24. }
  25. }

8、测试效果

好了,接下来我们定义一个接口来测试效果如何。

  1. package com.example.commonswitch.controller;
  2. import com.example.commonswitch.service.RegService;
  3. import com.example.commonswitch.util.Result;
  4. import lombok.AllArgsConstructor;
  5. import org.springframework.web.bind.annotation.PostMapping;
  6. import org.springframework.web.bind.annotation.RequestMapping;
  7. import org.springframework.web.bind.annotation.RestController;
  8. /**
  9. * <p>
  10. * 挂号接口
  11. * </p>
  12. *
  13. * @author 程序员济癫
  14. * @since 2023-10-16 18:51
  15. */
  16. @RestController
  17. @RequestMapping("/api/reg")
  18. @AllArgsConstructor
  19. public class RegController {
  20. private final RegService regService;
  21. @PostMapping("/createOrder")
  22. public Result createOrder() {
  23. return regService.createOrder();
  24. }
  25. }

Redis中把开关加上去(实际工作中是后台添加的哈),此时开关是1,表示开关打开。

image

调接口,可以发现,目前是正常的业务流程。

image

接下来,我们假定线上出了问题,要立马将开关关闭。(还是操作Redis,实际工作中是后台直接关掉哈)

我们将其改为0,也就是表示开关给关闭。

image

看效果,OK,没问题,是我们预想的结果。

image

这里要记住一点,提示可以自定义,但是不要直接返回给用户系统异常,给一个友好提示即可。

总结

文中使用到的技术主要是这些:SpringBoot、自定义注解、AOP、Redis、Lombok。

其中,自定义注解和AOP是核心实现,Redis是可选项,你也可以接入到数据库。

lombok的话大家可以仔细看代码,我用它帮助省略了所有@Autowaird,这样就使用了官方及IDEA推荐的构造器注入方式。

好了,今天的小案例,xdm学会了吗。


如果喜欢,请点赞+关注↓↓↓,持续分享干货哦!

原文链接:https://www.cnblogs.com/fulongyuanjushi/p/17768637.html

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号