动态代理-annotation结合

本文介绍了一种基于Java的重试机制实现方案。通过自定义注解`@DoRetry`来标记需要重试的方法,并利用`InvocationHandler`和`Proxy`创建代理对象,实现了方法级别的重试逻辑。此方案可根据需要配置重试次数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface DoRetry {

    /**
     * 重试次数
     * @return
     */
    int times() default 1;
    
}


public class RetryProxy implements InvocationHandler {
    
    private static final Logger LOGGER = LoggerFactory.getLogger(RetryProxy.class);
    
    private Object object;
    
    @SuppressWarnings("unchecked")
    public <T> T getInstance(T t) {
        object = t;
        return (T)Proxy.newProxyInstance(t.getClass().getClassLoader(), t.getClass().getInterfaces(), this);
    }
 
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        int times = method.getAnnotation(DoRetry.class).times();
        Object result = null;
        while (times-- > 0) {
            try {
                LOGGER.info("重试目标对象:{}, 目标方法:{}, 参数:{}", object.getClass().getName(), method.getName(), JsonUtils.toJSON(args));
                result = method.invoke(object, args);
                break;
            } catch (Exception e) {
                LOGGER.error("Error happend, retry", e);
            }
        }
        return result;
    }
    
}


@Resource
protected NotifyManager httpNotifyManager;


NotifyManager notifyManager = new RetryProxy().getInstance(httpNotifyManager);
notifyManager.notifies(req, notifyUrl);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值