SpringBoot + 自定义注解 + AOP 打造通用开关

这篇具有很好参考价值的文章主要介绍了SpringBoot + 自定义注解 + AOP 打造通用开关。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

前言

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

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

案例

1、项目结构

SpringBoot + 自定义注解 + AOP 打造通用开关,spring boot,java,aop

2、引入依赖
<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-redis</artifactId>
        </dependency>
    </dependencies>
3、yml配置

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

server:
  port: 8888

spring:
  redis:
    database: 6
    host: XX.XX.XX.XX
    port: 6379
    password:
    jedis:
      pool:
        max-active: 100
        max-wait: -1ms
        max-idle: 50
        min-idle: 1
4、自定义注解

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

package com.wang.annotation;
import com.wang.constant.Constant;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
 * @projectName: spring-study
 * @package: com.wang.annotation
 * @className: ServiceSwitch
 * @author: wangwujie
 * @description: TODO
 * @date: 2024-1-18 10:30
 */

@Target({ElementType.METHOD})  // 作用在方法上
@Retention(RetentionPolicy.RUNTIME)  // 运行时起作用
public @interface ServiceSwitch {

    /**
     * 业务开关的key(不同key代表不同功效的开关)
     * {@link Constant.ConfigCode}
     */
    String switchKey();

    // 开关,0:关(拒绝服务并给出提示),1:开(放行)
    String switchVal() default "0";

    // 提示信息,默认值可在使用注解时自行定义。
    String message() default "当前请求人数过多,请稍后重试。";
}

5、AOP核心实现

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

package com.wang.aop;

import com.wang.annotation.ServiceSwitch;
import com.wang.constant.Constant;
import com.wang.exception.BusinessException;
import com.wang.utils.Result;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @projectName: spring-study
 * @package: com.wang.aop
 * @className: ServiceSwitchAOP
 * @author: wangwujie
 * @description: TODO
 * @date: 2024-1-18 10:32
 */

@Aspect
@Component
@Slf4j
@AllArgsConstructor
public class ServiceSwitchAOP {

    private final StringRedisTemplate redisTemplate;

    /**
     * 定义切点,使用了@ServiceSwitch注解的类或方法都拦截
     */
    @Pointcut("@annotation(com.wang.annotation.ServiceSwitch)")
    public void pointcut() {
    }

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint point) {

        // 获取被代理的方法的参数
        Object[] args = point.getArgs();
        // 获取被代理的对象
        Object target = point.getTarget();
        // 获取通知签名
        MethodSignature signature = (MethodSignature) point.getSignature();

        try {

            // 获取被代理的方法
            Method method = target.getClass().getMethod(signature.getName(), signature.getParameterTypes());
            // 获取方法上的注解
            ServiceSwitch annotation = method.getAnnotation(ServiceSwitch.class);

            // 核心业务逻辑
            if (annotation != null) {

                String switchKey = annotation.switchKey();
                String switchVal = annotation.switchVal();
                String message = annotation.message();

            /*
              获取配置项说明
              这里有两种方式:1、配置加在Redis,查询时从Redis获取;
                          2、配置加在数据库,查询时从表获取。(MySQL单表查询其实很快,配置表其实也没多少数据)
              我在工作中的做法:直接放到数据库,但是获取配置项的方法用SpringCache缓存,
                           然后在后台管理中操作配置项,变更时清理缓存即可。
                           我这么做就是结合了上面两种各自的优点,因为项目中配置一般都是用后台管理来操作的,
                           查表当然更舒适,同时加上缓存提高查询性能。
             */

                // 下面这块查询配置项,大家可以自行接入并修改。
                // 数据库这么查询:String configVal = systemConfigService.getConfigByKey(switchKey);
                // 这里我直接从redis中取,使用中大家可以按照意愿自行修改。
                String configVal = redisTemplate.opsForValue().get(Constant.ConfigCode.REG_PAY_SWITCH);
                if (switchVal.equals(configVal)) {
                    // 开关打开,则返回提示。
                    return new Result<>(HttpStatus.FORBIDDEN.value(), message);
                }
            }

            // 放行
            return point.proceed(args);

        } catch (Throwable e) {
            throw new BusinessException(e.getMessage(), e.getMessage());
        }
    }
}

6、定义常量

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

package com.wang.constant;

/**
 * @projectName: spring-study
 * @package: com.wang.constant
 * @className: Constant
 * @author: wangwujie
 * @description: TODO
 * @date: 2024-1-18 10:31
 */

public class Constant {

    // .... 其他业务相关的常量 ....

    // 配置相关的常量
    public static class ConfigCode {

        // 挂号支付开关(0:关,1:开)
        public static final String REG_PAY_SWITCH = "reg_pay_switch";
        // 门诊支付开关(0:关,1:开)
        public static final String CLINIC_PAY_SWITCH = "clinic_pay_switch";

        // 其他业务相关的配置常量
        // ....
    }
}

7、使用注解

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

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

package com.wang.service;

import com.wang.annotation.ServiceSwitch;
import com.wang.constant.Constant;
import com.wang.utils.Result;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;

/**
 * @projectName: spring-study
 * @package: com.wang.service
 * @className: RegService
 * @author: wangwujie
 * @description: TODO
 * @date: 2024-1-18 10:32
 */
@Service
public class RegService {

    /**
     * 挂号下单
     */
    @ServiceSwitch(switchKey = Constant.ConfigCode.REG_PAY_SWITCH)
    public Result createOrder() {

        // 具体下单业务逻辑省略....

        return new Result(HttpStatus.OK.value(), "挂号下单成功");
    }
}

8、统一返回类Result

设置统一请求返回Result,以及ResultCode枚举类,用来处理统一返回请求参数。

package com.wang.utils;

/**
 * @projectName: spring-study
 * @package: com.wang.utils
 * @className: ResultCode
 * @author: wangwujie
 * @description: TODO
 * @date: 2024-1-18 10:46
 */
public enum ResultCode {
    SUCCESS(0, "Success"),
    ERROR(1, "Error");
    // 其他状态码...

    private final int code;
    private final String message;

    ResultCode(int code, String message) {
        this.code = code;
        this.message = message;
    }

    public int getCode() {
        return code;
    }

    public String getMessage() {
        return message;
    }
    }

package com.wang.utils;

import lombok.Data;

/**
 * @projectName: spring-study
 * @package: com.wang.utils
 * @className: Result
 * @author: wangwujie
 * @description: TODO
 * @date: 2024-1-18 10:34
 */
@Data
public class Result<T> {
    private int code;
    private String message;
    private T data;

    public Result(int code, String message) {
        this.code = code;
        this.message = message;
    }

    public Result(int code, String message,T data) {
        this.code = code;
        this.message = message;
        this.data = data;
    }

    // 构造方法,getter和setter省略

    public static <T> Result<T> success() {
        return new Result<>(ResultCode.SUCCESS.getCode(), ResultCode.SUCCESS.getMessage());
    }

    public static <T> Result<T> success(T data) {
        return new Result<>(ResultCode.SUCCESS.getCode(), ResultCode.SUCCESS.getMessage(), data);
    }

    public static <T> Result<T> error(ResultCode resultCode) {
        return new Result<>(resultCode.getCode(), resultCode.getMessage());
    }

    public static <T> Result<T> error(ResultCode resultCode, String message) {
        return new Result<>(resultCode.getCode(), message);
    }
}

9、全局异常处理

设置全局异常BusinessException类,以及全局异常处理类GlobalExceptionHandler。

package com.wang.exception;

/**
 * @projectName: spring-study
 * @package: com.wang.exception
 * @className: BusinessException
 * @author: wangwujie
 * @description: TODO
 * @date: 2024-1-18 14:26
 */
public class BusinessException extends RuntimeException {

    private final String code;

    public BusinessException(String code, String message) {
        super(message);
        this.code = code;
    }

    public String getCode() {
        return code;
    }
}

package com.wang.exception;

/**
 * @projectName: spring-study
 * @package: com.wang.exception
 * @className: GlobalExceptionHandler
 * @author: wangwujie
 * @description: TODO
 * @date: 2024-1-18 14:22
 */
import com.wang.utils.Result;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(BusinessException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResponseEntity<Result<Object>> handleBusinessException(BusinessException ex) {
        Result<Object> result = new Result<>(Integer.getInteger(ex.getCode()), ex.getMessage(), null);
        return new ResponseEntity<>(result, HttpStatus.BAD_REQUEST);
    }

    // 可以添加其他异常处理方法...

}

8、测试效果-controller

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

package com.wang.controller;

/**
 * @projectName: spring-study
 * @package: com.wang.controller
 * @className: RegController
 * @author: wangwujie
 * @description: TODO
 * @date: 2024-1-18 10:33
 */
import com.wang.service.RegService;
import com.wang.utils.Result;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api")
@AllArgsConstructor
public class RegController {

    private final RegService regService;

    @GetMapping("/createOrder")
    public Result createOrder() {

        return regService.createOrder();
    }
}

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

SpringBoot + 自定义注解 + AOP 打造通用开关,spring boot,java,aop

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

SpringBoot + 自定义注解 + AOP 打造通用开关,spring boot,java,aop

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

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

SpringBoot + 自定义注解 + AOP 打造通用开关,spring boot,java,aop

SpringBoot + 自定义注解 + AOP 打造通用开关,spring boot,java,aop

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

总结

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

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

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

好了,今天的小案例,xdm学会了吗。文章来源地址https://www.toymoban.com/news/detail-819108.html

到了这里,关于SpringBoot + 自定义注解 + AOP 打造通用开关的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • Spring Boot入门(23):基于AOP实现自定义注解拦截接口日志并保存入库 | 超级详细,建议收藏

            在上两期中,我们着重介绍了如何集成使用 Logback 与 log4j2 日志框架的使用,今天我们讲解的主题依旧跟日志有关,不过不是使用何种开源框架,而是自己动手造。         Spring的核心之一AOP;AOP翻译过来叫面向切面编程, 核心就是这个切面. 切面表示从业务逻辑中

    2024年02月11日
    浏览(35)
  • spring boot 使用AOP+自定义注解+反射实现操作日志记录修改前数据和修改后对比数据,并保存至日志表

    使用FieldMeta自定义注解,看个人业务自行觉得是否需要重新定义实体 实现类 :通过该实现类获取更新前后的数据。 该实现类的实现原理为:获取入参出入的id值,获取sqlSessionFactory,通过sqlSessionFactory获取selectByPrimaryKey()该方法,执行该方法可获取id对应数据更新操作前后的数

    2024年01月23日
    浏览(41)
  • spring自定义注解+aop+@BindingParam

    2.1 声明切面注解  2.1.1切面对应枚举  2.2 声明绑定参数注解 4.1 ThreadLocalUtil  4.2  自定义异常

    2024年02月14日
    浏览(30)
  • springboot aop 自定义注解形式

    2024年01月25日
    浏览(29)
  • 【Spring】使用自定义注解方式实现AOP鉴权

    AOP,是一种面向切面编程,可以通过预编译方式和运行期间动态代理实现程序功能的统一维护的一种技术。 在软件开发中,鉴权(Authentication)是一项非常重要的安全措施,用于验证用户身份和权限。在应用程序中,我们通常会使用AOP(Aspect-Oriented Programming)来实现鉴权功能

    2024年02月11日
    浏览(39)
  • 【SpringBoot】AOP 自定义注解的使用详解

            Spring 中的切面 Aspect,这是 Spring 的一大优势。面向切面编程往往让我们的开发更加低耦合,也大大减少了代码量,同时呢让我们更专注于业务模块的开发,把那些与业务无关的东西提取出去,便于后期的维护和迭代。         AOP 的全称为 Aspect Oriented Programming,

    2024年02月05日
    浏览(32)
  • springboot自定义注解+aop+redis实现延时双删

    redis作为用的非常多的缓存数据库,在多线程场景下,可能会出现数据库与redis数据不一致的现象 数据不一致的现象:https://blog.csdn.net/m0_73700925/article/details/133447466 这里采用aop+redis来解决这个方法: 删除缓存 更新数据库 延时一定时间,比如500ms 删除缓存 这里之所以要延时一

    2024年01月17日
    浏览(32)
  • spring-自定义AOP面向切面注解--统一切面处理-登陆信息采集

    2023华为OD统一考试(A+B卷)题库清单-带答案(持续更新)or2023年华为OD真题机考题库大全-带答案(持续更新) 1. 先写一个登陆记录注解(//记录:XXX时间,XXX姓名,XX系统,登录成功) 2. 写一个切面对注解进行处理(业务逻辑处理,记录登陆的信息) 3.写一个登录的控制类,

    2024年02月13日
    浏览(25)
  • 对接第三方接口鉴权(Spring Boot+Aop+注解实现Api接口签名验证)

    一个web系统,从接口的使用范围也可以分为对内和对外两种,对内的接口主要限于一些我们内部系统的调用,多是通过内网进行调用,往往不用考虑太复杂的鉴权操作。但是,对于对外的接口,我们就不得不重视这个问题,外部接口没有做鉴权的操作就直接发布到互联网,而

    2024年04月29日
    浏览(63)
  • springboot3使用自定义注解+AOP+redis优雅实现防重复提交

      ⛰️个人主页:     蒾酒 🔥 系列专栏 :《spring boot实战》 🌊 山高路远,行路漫漫,终有归途 目录 写在前面 实现思路 实现步骤 1.定义防重复提交注解 2.编写一个切面去发现该注解然后执行防重复提交逻辑 3.测试 依赖条件 1.接口上标记防重复提交注解 2.接口测试 写在最

    2024年04月11日
    浏览(32)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包