项目中使用@Retryable注解代替重试功能
package com.kittlen.cloud.service2;
import entities.Result;
import lombok.extern.slf4j.Slf4j;
import org.aopalliance.intercept.Interceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.retry.annotation.EnableRetry;
import org.springframework.retry.annotation.Retryable;
import org.springframework.retry.backoff.UniformRandomBackOffPolicy;
import org.springframework.retry.interceptor.MethodInvocationRecoverer;
import org.springframework.retry.interceptor.RetryInterceptorBuilder;
import org.springframework.stereotype.Service;
import util.base.StringUtil;
@Slf4j
@Service
@EnableRetry
public class RetryService {
@Bean("myInterceptor")
public Interceptor interceptor() {
UniformRandomBackOffPolicy policy = new UniformRandomBackOffPolicy();
MethodInvocationRecoverer<?> recoverer = (MethodInvocationRecoverer<Object>) (args, cause) -> Result.error("失败");
return RetryInterceptorBuilder.stateless().maxAttempts(5).
backOffPolicy(policy).
recoverer(recoverer).
build();
}
@Retryable(value = RuntimeException.class, interceptor = "myInterceptor")
public Result<String> test(String name) {
log.info("test");
if (StringUtil.isEmpty(name)) {
throw new RuntimeException("error");
}
return Result.ok();
}
public Result<String> test2(String name) {
for (int i = 0; i < 5; i++) {
try {
log.info("test2");
if (StringUtil.isEmpty(name)) {
throw new RuntimeException("error");
}
return Result.ok();
} catch (RuntimeException e) {
}
}
return Result.error("失败");
}
}