0
点赞
收藏
分享

微信扫一扫

spring重试注解入门Retryable

343d85639154 2022-04-06 阅读 56
spring

需求场景

有时候业务上需要一个简单的重试机制,这个时候写try catch递归的话容易增加代码复杂度。此时直接上springRetryable aopOK了.

代码demo

package com.felix.spring_cloud_one.service;

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

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Service
public class RetryableService {


    @Retryable(value = Exception.class, maxAttempts = 4, backoff = @Backoff(delay = 2000, multiplier = 3))
    public void retryable() {
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        System.out.println("当前时间为:" + dateTimeFormatter.format(LocalDateTime.now()));
        throw new RuntimeException("测试");
    }
}

运行结果
在这里插入图片描述

来简单解释一下注解中几个参数的含义:

  1. value:抛出指定异常才会重试
  2. include:和value一样,默认为空,当exclude也为空时,默认所有异常
  3. exclude:指定不处理的异常
  4. maxAttempts:最大重试次数,默认3次
  5. backoff:重试等待策略,默认使用@Backoff,@Backoff的value默认为1000L,我们设置为2000L;
  6. multiplier(指定延迟倍数)默认为0,表示固定暂停1秒后进行重试,如果把multiplier设置为2,则第一次重试为2秒(delay 指定时间),第二次为4(multiplier X delay)秒,第三次为8(3 X multiplier X delay)秒。
举报

相关推荐

0 条评论