Spring Boot + AOP + 自定义注解 设置接口开关

使用自定义注解,再用AOP切面,完成控制接口的开关。感觉挺有意思的。

直接上案例

Redis存储了这个接口的key,1表示放开,0表示关闭。

下图所示表示放开接口。
在这里插入图片描述
使用Postman调用接口,成功。
在这里插入图片描述
将Redis对应的value改为0(实际开发中是后台管理),在调用一次。
在这里插入图片描述
接口关闭。这样就可以轻松管理接口的开放与关闭了。

代码

首先看一下整体框架
在这里插入图片描述

annotation

package com.xmr.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

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

    // 业务开关key
    String switchKey();

    // 开关:0表示关,1表示开,放行
    String switchVal() default "0";

    // 提示信息
    String message() default "该接口关闭!";
}

constant

package com.xmr.constant;

public class Constant {
    public static class ConfigCode{

        // AI服务
        public static final String AI_Service_SWITCH = "ai_service_switch";

        // 其他业务配置……
    }
}

aop

package com.xmr.aop;

import com.xmr.annotation.ServiceSwitch;
import com.xmr.constant.Constant;
import jakarta.annotation.Resource;
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.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Aspect
@Component
public class ServiceSwitchAOP{

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 定义切点,使用了@ServiceSwitch注解的类或方法都拦截
     */
    @Pointcut("@annotation(com.xmr.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,下面的做法
                // 方法2:放在数据库
                String configVal = redisTemplate.opsForValue().get(Constant.ConfigCode.AI_Service_SWITCH);
                if (switchVal.equals(configVal)) {
                    // 开关打开,则返回提示。
                    // 表示开关关闭,为0
                    return message;
                }
            }

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

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

    }
}

这里有两种方式:

  1. 配置加在Redis,查询时从Redis获取;
  2. 配置加在数据库,查询时从表获取。
  3. 优化方法:直接放到数据库,但是获取配置项的方法用SpringCache缓存,变更时要清理缓存。

Controller

package com.xmr.Controller;
import com.xmr.service.AiService;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 调用Ai接口
 */
@RestController
@RequestMapping("/api")
@AllArgsConstructor
public class AiController {

   private final AiService aiService;

   @PostMapping("/Ai")
   public String createOrder() {

      return aiService.createOrder();
   }
}

Service

package com.xmr.service;

import com.xmr.annotation.ServiceSwitch;
import com.xmr.constant.Constant;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;

@Service
public class AiService {

   /**
    * 调用AI服务
    */
   @ServiceSwitch(switchKey = Constant.ConfigCode.AI_Service_SWITCH)
   public String createOrder() {

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

      return "调用AI服务成功";
   }
}

yml配置

server:
  port: 8080
spring:
  data:
    redis:
      database: 0
      host: localhost
      port: 6379

  • 10
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Spring Boot中使用AOP自定义注解可以帮助我们更方便地进行方法的拦截和处理。下面是一种最佳实践过程: 1. 首先,我们需要引入`spring-boot-starter-aop`依赖。可以在`pom.xml`文件中添加如下内容: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency> ``` 2. 创建一个自定义注解。可以使用`@interface`关键字创建一个注解类,并在注解类中定义需要的属性。例如: ```java @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface MyAnnotation { // 定义需要的属性 } ``` 3. 创建一个切面类。切面类用来定义需要进行拦截和处理的方法。可以使用`@Aspect`注解标记该类,并使用`@Around`注解指定要拦截处理的目标方法。例如: ```java @Aspect @Component public class MyAspect { @Around("@annotation(com.example.MyAnnotation)") public Object aroundMethod(ProceedingJoinPoint joinPoint) throws Throwable { // 在方法执行前进行处理 // ... Object result = joinPoint.proceed(); // 在方法执行后进行处理 // ... return result; } } ``` 4. 在Spring Boot的启动类上添加`@EnableAspectJAutoProxy`注解,开启AOP的支持。例如: ```java @SpringBootApplication @EnableAspectJAutoProxy public class Application { // ... } ``` 5. 在需要应用切面的方法上添加自定义注解。 ```java @MyAnnotation public void someMethod() { // ... } ``` 通过以上步骤,我们就可以成功地在Spring Boot中使用AOP自定义注解来进行方法的拦截和处理了。需要注意的是,如果定义的注解只用于标记方法,而不需要定义属性,可以简化为一个空接口
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值