ITeye博客

spring boot 重试

chzhxu · 2018-04-03 15:29 · spring · 编程语言 · Markdown


		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.retry</groupId>
			<artifactId>spring-retry</artifactId>
		</dependency>
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjweaver</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.remoting.RemoteAccessException;
import org.springframework.retry.annotation.EnableRetry;
import org.springframework.retry.annotation.Retryable;

@Configuration
@EnableRetry
public class Application {



}


import java.time.LocalTime;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.remoting.RemoteAccessException;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Recover;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;

@Service
public class RemoteService {
    
    private final static Logger logger = LoggerFactory.getLogger(RemoteService.class);
    
    @Retryable(value = { RemoteAccessException.class }, maxAttempts = 3, backoff = @Backoff(delay = 5000l, multiplier = 1))
    public int call() throws Exception {
        logger.info(LocalTime.now()+" do something...");
//        throw new RemoteAccessException("RPC调用异常");
        throw new RuntimeException("run errer");
    }

    @Recover
    public int recover(RemoteAccessException e) {
        logger.info("================10=========================="+e.getMessage());

        return 10;
    }

    @Recover
    public int recover(RuntimeException e) {
        logger.info("============12=============================="+e.getMessage());
        return 12;
    }

    @Recover
    public int recover(Exception e) {
        logger.info("============11=============================="+e.getMessage());
        return 11;
    }
}


** @Retryable注解 被注解的方法发生异常时会重试 value:指定发生的异常进行重试 include:和value一样,默认空,当exclude也为空时,所有异常都重试 exclude:指定异常不重试,默认空,当include也为空时,所有异常都重试 maxAttemps:重试次数,默认3 backoff:重试补偿机制,默认没有

@Backoff注解 delay:指定延迟后重试 multiplier:指定延迟的倍数,比如delay=5000l,multiplier=2时,第一次重试为5秒后,第二次为10秒,第三次为20秒

@Recover 当重试到达指定次数时,被注解的方法将被回调,可以在该方法中进行日志处理。需要注意的是发生的异常和入参类型一致时才会回调 **

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。