Java中动态修改注解的值

本文介绍了如何通过Java反射技术,实现在运行时动态修改`@RateLimit`注解的流量值,以适应场景需求的变化。作者提供了工具类和切面处理的代码示例,展示了如何获取注解、更新成员值以及在API请求中应用这些变化。
摘要由CSDN通过智能技术生成

1. 描述

部分场景需要动态修改注解的值。例如,我们使用自定义注解控制接口流量,如果需要动态修改流量值,可以使用反射的方法实现。

2. 步骤

  • 获取注解
  • 从注解中获取memberValues属性(map)
  • 使用put方法更新对象的值

3. 代码实现

该部分代码主要是基于流量控制的功能demo,使用反射动态修改@RateLimit注解达到动态修改流量的目的。此章节节选了反射修改值的代码予以分享。

3.1 主工具类

import com.hz.common.aop.limit.RateLimit;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.util.Map;

/**
 * @author pp_lan
 * @date 2024/2/3
 */
public class ReflectUtils {

    private ReflectUtils() {
    }

    public static void dynamicLocation(RateLimit rateLimit, String fileName, Object fieldValue) throws IllegalAccessException, NoSuchFieldException {

        if (rateLimit == null) {
            return;
        }

        InvocationHandler invocationHandler = Proxy.getInvocationHandler(rateLimit);
        Class<? extends InvocationHandler> aClass = invocationHandler.getClass();

        Field memberValues = aClass.getDeclaredField("memberValues");
        memberValues.setAccessible(true);
        Map<String, Object> menberValueMap = (Map<String, Object>) memberValues.get(invocationHandler);
        menberValueMap.put(fileName, fieldValue);
    }
}

3.2 依赖

3.2.1 RateLimit

import java.lang.annotation.*;

/**
 * @author pp_lan
 */
@Documented
@Inherited
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface RateLimit {

    /**
     * 名称
     *
     * @return
     */
    String name();

    /**
     * 每分钟限流数量
     *
     * @return
     */
    int limitNum();

}

3.2.2 切面处理

切面中需要动态获取注解

@Component
public class RateLimitAspect {

    private static final Logger LOGGER = LoggerFactory.getLogger(RateLimitAspect.class);

    private ConcurrentHashMap<String, RateLimiter> limitMap = new ConcurrentHashMap<>();

    @Pointcut("@annotation(com.hz.common.aop.limit.RateLimit) && @annotation(rateLimit)")
    public void pointCut(RateLimit rateLimit){}

    @Around(value = "pointCut(rateLimit)")
    public Object around(ProceedingJoinPoint joinPoint, RateLimit rateLimit) throws Throwable {

        // 此处动态获取注解值取代初始化的RateLimit值
        Object target = joinPoint.getTarget();
        MethodSignature sig = (MethodSignature) joinPoint.getSignature();
        Method currentMethod = target.getClass().getMethod(sig.getName(), sig.getParameterTypes());
        RateLimit newRateLimit = currentMethod.getAnnotation(RateLimit.class);
        LOGGER.info("[限流器{}]{}", newRateLimit.name(), newRateLimit.limitNum());
        boolean isLimited = limitByKey(newRateLimit.name(), newRateLimit.limitNum());
        if (isLimited) {
            throw new RateLimitException(String.format("【限流了】%s", newRateLimit.name()));
        }

        return joinPoint.proceed();
    }

    /**
     * 是否被限流
     *
     * @param key
     * @param limitNum
     * @return
     */
    private boolean limitByKey(String key, Integer limitNum) {
       ...
    }

}

3.3 使用

5-7行获取注解,并修改注解中属性的值

@RequestMapping("/updateLimitRate")
public Response editLimitRate(Integer methodType, Integer limitNum) throws NoSuchMethodException, NoSuchFieldException, IllegalAccessException {

        String methodName = methodType == 1 ? "queryAllUser": "test";
        Method method = UserService.class.getMethod(methodName);
        RateLimit annotation = method.getAnnotation(RateLimit.class);
        ReflectUtils.dynamicLocation(annotation, "limitNum", limitNum);
        return Response.ok();
}

4. 效果

4.1 初始化的桶大小

4.2 限流提示

4.3 动态更改流量值

4.4 重新访问

不再限流,接口可以继续正常访问了。

  • 6
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
首先,需要获取到需要修改注解的类的Class对象。然后,通过该Class对象的getDeclaredField()方法获取需要修改注解的字段,再通过该字段的getAnnotations()方法获取所有注解,接着遍历注解数组,找到需要修改注解,使用Java反射的Proxy.newProxyInstance()方法创建一个代理对象,并在代理对象实现InvocationHandler接口,在invoke()方法修改注解。最后,通过反射调用setAnnotation()方法将修改后的注解设置回原字段。 以下是示例代码: ``` // 获取Class对象 Class<?> clazz = MyClass.class; // 获取需要修改注解的字段 Field field = clazz.getDeclaredField("myField"); // 获取所有注解 Annotation[] annotations = field.getAnnotations(); // 遍历注解数组 for (Annotation annotation : annotations) { // 判断是否需要修改注解 if (annotation.annotationType() == MyAnnotation.class) { // 创建代理对象 Object proxy = Proxy.newProxyInstance(annotation.getClass().getClassLoader(), new Class[]{annotation.annotationType()}, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // 修改注解 if (method.getName().equals("value")) { return "new value"; } else { return method.invoke(annotation, args); } } }); // 将修改后的注解设置回原字段 field.setAnnotation((MyAnnotation) proxy); } } ``` 需要注意的是,修改注解是在代理对象的invoke()方法实现的,需要根据注解的属性名称进行判断和修改。同时,由于注解是不可变的,因此需要使用代理对象来动态修改注解的属性

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值