springboot 一行代码引入重试机制

直接上代码

1.pom文件中引入依赖

<dependency>
    <groupId>org.springframework.retry</groupId>
    <artifactId>spring-retry</artifactId>
</dependency>

2.开启重试

启动类上加

@EnableRetry

3.方法上加注解

@Retryable(value = Exception.class, maxAttempts = 3, backoff = @Backoff(delay = 500L, maxDelay = 3000L, multiplier = 2, random = true))

4.示例代码

package pers.wwz.oom.oomone.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Retryable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import pers.wwz.oom.oomone.service.RetryService;

import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
@RequestMapping("/retry")
@RestController
public class RetryController {

    private AtomicInteger requestCount = new AtomicInteger(1);

    @Autowired
    RetryService retryService;


    /**
     * 重试
     * @return
     */
    @Retryable(value = Exception.class, maxAttempts = 3, backoff = @Backoff(delay = 500L, maxDelay = 3000L, multiplier = 2, random = true))
    @RequestMapping("/helloWorld")
    public Integer helloWorld(){

        int requestCountTmp = requestCount.get();
        if(requestCountTmp>1){
            return requestCountTmp;
        }else {
            requestCount.addAndGet(1);
            log.info("错误:{}",1/0);
            return helloWorld();
        }
    }

    /**
     * service重试
     * @return
     */
    @RequestMapping("/serviceRetry")
    public Integer serviceRetry(){
        return retryService.serviceRetry();
    }
}
package pers.wwz.oom.oomone.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;

import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
@Service
public class RetryService {


    private AtomicInteger requestCount = new AtomicInteger(1);

    @Retryable(value = Exception.class, maxAttempts = 3, backoff = @Backoff(delay = 500L, maxDelay = 3000L, multiplier = 2, random = true))
    public int serviceRetry(){
        int requestCountTmp = requestCount.get();
        if(requestCountTmp>1){
            return requestCountTmp;
        }else {
            requestCount.addAndGet(1);
            log.info("错误:{}",1/0);
            return serviceRetry();
        }
    }
}

猜你喜欢

转载自blog.csdn.net/wangwenzhe222/article/details/130156490