SpringBoot整合spring-retry实现重试

SpringBoot整合spring-retry实现重试

1. jar导入

  • 除了引入spring-retry外,还需要使用spring-aspects
implementation 'org.springframework.retry:spring-retry'
implementation 'org.springframework:spring-aspects'

2. 启动类添加@EnableRetry注解

package com.example.fisher.gradledemo;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.retry.annotation.EnableRetry;

import lombok.extern.slf4j.Slf4j;

@EnableRetry
@MapperScan("com.example.fisher.gradledemo.*.dao")
@SpringBootApplication
public class GradleDemoApplication {
    
    

    public static void main(String[] args) {
    
    
        SpringApplication.run(GradleDemoApplication.class, args);
    }

}

3. service类具体实现

  • @Retryable下参数说明
    recover:指定重试失败后,回调的具体方法
    value:指定出现哪种异常才重试
    maxAttempts:指定方法执行次数,默认是执行3次
    backoff:补偿机制
  • @Backoff下参数说明
    delay:指定执行的延迟时间
    multiplier:延迟时间的倍数
package com.example.fisher.gradledemo.retry.service.impl;

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

import com.example.fisher.gradledemo.retry.service.RetryService;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service("retryService")
public class RetryServiceImpl implements RetryService {
    
    

    @Retryable(recover = "recoverMethod", maxAttempts = 3, value = Exception.class,
        backoff = @Backoff(delay = 1000L, multiplier = 2))
    @Override
    public String retry(String msg) {
    
    
        log.info("msg={}", msg);
        int i = 1 / 0;
        return msg;
    }

    @Recover
    public String recoverMethod(Exception exception, String msg) {
    
    
        log.error("recoverMethod: param={}", msg, exception);
        return "recover";
    }
}

4. controller类

package com.example.fisher.gradledemo.retry.controller;

import com.example.fisher.gradledemo.retry.service.RetryService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

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

    @Resource
    private RetryService retryService;

    @GetMapping
    public String retryTest(@RequestParam String msg) {
    
    
        String retry = retryService.retry(msg);
        return retry;
    }

}

5. 启动项目,调用接口

  • 查看打印

在这里插入图片描述

  • 延迟执行,1s和2s

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_40977118/article/details/120459101
今日推荐