动态代理-annotation结合

@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);

你可能感兴趣的:(Spring)