目录

chen 的个人博客

VX:ZzzChChen
Phone:13403656751
Email:zxydczzs@gmail.com

X

Spring Retry && Guava Retry

Spring Retry

一、引入 Maven 依赖
 1        <!-- https://mvnrepository.com/artifact/org.springframework.retry/spring-retry -->
 2        <dependency>
 3            <groupId>org.springframework.retry</groupId>
 4            <artifactId>spring-retry</artifactId>
 5            <version>1.3.1</version>
 6        </dependency>
 7        <!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
 8        <dependency>
 9            <groupId>org.aspectj</groupId>
10            <artifactId>aspectjweaver</artifactId>
11            <version>1.9.7</version>
12        </dependency>
二、EnableRetry 注解
 1package com.zxy.demo;
 2
 3import org.springframework.boot.SpringApplication;
 4import org.springframework.boot.autoconfigure.SpringBootApplication;
 5import org.springframework.retry.annotation.EnableRetry;
 6
 7@SpringBootApplication
 8@EnableRetry
 9public class DemoApplication {
10
11    public static void main(String[] args) {
12        SpringApplication.run(DemoApplication.class, args);
13
14    }
15
16}
17
三、在需要重试的方法添加 @Retryable 注解
 1package com.zxy.demo.service.impl;
 2
 3import cn.hutool.core.date.DateUtil;
 4import com.zxy.demo.service.RetryService;
 5import org.springframework.retry.RetryException;
 6import org.springframework.retry.annotation.Backoff;
 7import org.springframework.retry.annotation.Recover;
 8import org.springframework.retry.annotation.Retryable;
 9import org.springframework.stereotype.Service;
10
11/**
12 * @description: study
13 * 模块名称:
14 * 说明:
15 * 作者(@author): zxy
16 * 创建日期:
17 */
18
19@Service
20public class RetryServiceImpl implements RetryService {
21    @Override
22    @Retryable(value = {RetryException.class}, maxAttempts = 5, backoff = @Backoff(delay = 5000L, multiplier = 2))
23    public void test(String str) {
24        System.out.println("retry------test:" + str);
25        System.out.println(DateUtil.now());
26        throw new RetryException("发生异常");
27    }
28
29    @Recover
30    private void recover(RetryException e) {
31        System.out.println(e.getMessage());
32    }
33}
34

参数解释

@Retryable

  1. value:指定发生的异常进行重试;
  2. include:和 value 一样,默认空,当 exclude 也为空时,所有异常都重试;
  3. exclude:指定异常不重试,默认空,当 include 也为空时,所有异常都重试;
  4. maxAttemps:重试次数,默认为 3;
  5. backoff:重试补偿机制,默认没有

@Backoff

  1. delay:指定延迟后重试;
  2. multiplier:指定延迟的倍数,比如 delay = 5000L,multiplier=2 时,第一次重试为 5 秒后,第二次 10 秒,第三次为 20 秒。

@Recover

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

image.png

Guava Retry

一、引入 Maven 依赖
1        <!-- https://mvnrepository.com/artifact/com.github.rholder/guava-retrying -->
2        <dependency>
3            <groupId>com.github.rholder</groupId>
4            <artifactId>guava-retrying</artifactId>
5            <version>2.0.0</version>
6        </dependency>
二、代码展示
 1package com.zxy.demo.retry;
 2
 3import cn.hutool.core.date.DateUtil;
 4import com.github.rholder.retry.*;
 5import lombok.extern.slf4j.Slf4j;
 6
 7import java.util.concurrent.Callable;
 8import java.util.concurrent.ExecutionException;
 9import java.util.concurrent.TimeUnit;
10
11/**
12 * @description: study
13 * 模块名称:
14 * 说明: Retry Google Guava
15 * 作者(@author): zxy
16 * 创建日期: 2022年2月23日10:01:04
17 */
18@Slf4j
19public class RetryGuava {
20    public static void main(String[] args) throws Exception {
21
22        //定义重试机制
23        Retryer<Boolean> retryer = RetryerBuilder.<Boolean>newBuilder()
24                // retryIf 重试条件返回值为false
25//                .retryIfResult(Predicates.equalTo(false))
26                //设置异常重试源 发生具体异常
27                .retryIfExceptionOfType(Exception.class)
28                //设置等待间隔时间 没过几秒后进行重试
29//                .withWaitStrategy(WaitStrategies.fixedWait(3, TimeUnit.SECONDS))
30                // 每次重试递增时间量
31                .withWaitStrategy(WaitStrategies.incrementingWait(1, TimeUnit.SECONDS,2, TimeUnit.SECONDS))
32                //设置最大重试次数
33                .withStopStrategy(StopStrategies.stopAfterAttempt(3))
34                .build();
35        try {
36            retryer.call(() -> test());
37        } catch (RetryException | ExecutionException e) {
38            e.printStackTrace();
39        }
40    }
41
42    public static Boolean test() throws Exception {
43        String now = DateUtil.now();
44        System.out.println(now);
45        System.out.println("异常");
46        throw new Exception("发送异常,需要重试");
47//        return false;
48    }
49}
50

参数解释

retryIfResult

  1. 方法触发重试的结果,比如方法返回 null 或方法返回 false 等结果后触发重试操作。

retryIfExceptionOfType

  1. 方法发生异常后重试,可以指定具体异常。

withWaitStrategy

  1. 指定重试策略,比如 WaitStrategies.fixedWait(long sleepTime, TimeUnit timeUnit),比如设置了 5 秒,则每次重试的间隔都是五秒。
  2. WaitStrategies.incrementingWait(long initialSleepTime, TimeUnit initialSleepTimeUnit, long increment, TimeUnit incrementTimeUnit),时间量递增重试,比如参数为 1, TimeUnit.SECONDS,2, TimeUnit.SECONDS,则第二次间隔一秒,第三次间隔三秒,第四次间隔五秒,递增式增加时间量。

withStopStrategy

  1. 设置最大重试次数。

image.png

1    try {
2        retryer.call(() -> 发送某种错误后要重试的方法);
3    } catch (ExecutionException e) {
4        // 发生其他异常时触发;
5    } catch (RetryException e) {
6        // 重试完成后仍未拿到正确响应时触发,可以记录日志等操作;
7    }

标题:Spring Retry && Guava Retry
作者:zzzzchen
地址:https://www.dczzs.com/articles/2022/02/26/1645844978034.html