Spring 重试功能

     业务系统在调用其他系统服务或者外部服务时,为防止网络抖动或其它异常因素,需要引入重试机制确保服务调用更健壮,spring 提供了spring-retry支持重试机制,废话不多说,下面直接贴代码。

    1.pom引入

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

   2. 重试调用模拟

    

import org.springframework.retry.RecoveryCallback;
import org.springframework.retry.RetryCallback;
import org.springframework.retry.RetryContext;
import org.springframework.retry.RetryException;
import org.springframework.retry.backoff.FixedBackOffPolicy;
import org.springframework.retry.policy.SimpleRetryPolicy;
import org.springframework.retry.support.RetryTemplate;

import java.util.Random;

/**
 * spring 重试机制
 * @author test
 * @Time 2018/2/6.
 */
public class SpringRetryTest {


    /**
     * 模拟重试具体调用的方法(仅返回true则调用成功)
     * 通过随机数对基本参数求余后为3的整数则判断调用成功
     * @return
     */
    public static  boolean testRetry(int  modSeed){
        boolean  status=false;
        int randomInt=new Random().nextInt()%modSeed;
        System.out.println("当前随机数:"+randomInt);
        if(randomInt % 3==0){
            status=true;
        }
        return  status;
    }

    public static void main(String[] args) {
        RetryTemplate retryTemplate=new RetryTemplate();//重试机制
        SimpleRetryPolicy retryPolicy=new SimpleRetryPolicy();
        retryPolicy.setMaxAttempts(3);//设置最多重试次数
        retryTemplate.setRetryPolicy(retryPolicy);//设置重试策略
        FixedBackOffPolicy fixedBackOffPolicy=new FixedBackOffPolicy();
        fixedBackOffPolicy.setBackOffPeriod(3000l);
        retryTemplate.setBackOffPolicy(fixedBackOffPolicy);//设置重试延迟策略( 失败后多久重试)
        final  int modSeed=10;//重试参数必须为final
        try {
            Boolean obj=retryTemplate.execute(new RetryCallback<Boolean>() {
                 public Boolean doWithRetry(RetryContext retryContext) throws Exception {//重试具体方法
                     boolean isTripple= testRetry(modSeed);
                     if(!isTripple){
                         throw  new RetryException("调用服务错误");
                     }
                     //返回调用结果
                     return isTripple;
                 }
                 }, new RecoveryCallback<Boolean>() {
                     public Boolean recover(RetryContext retryContext) throws Exception {//重试多次后都失败的处理方法
                         return null;
                     }
                 }
            );
            System.out.println("服务调用结果obj:"+obj);
        }
        catch (Exception e){
            e.printStackTrace();
        }

    }

}

   3. 测试输出结果



   demo很简单,欢迎交流


   

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值