随笔:模拟rpc远程调用失败的重试

package com.example.demo.retry;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * 模拟rpc 远程失败后重试,
 * 有的busi方法是通过aop拦截器,拦截器中配置重试次数,读取注解中重试次数后,完成重试,也可以对重试加入sleep间隔
 */
public class RetryClz {

    public static void rpc(){
        throw new RuntimeException("rpc error:"+count.get());
    }

    public static void busi(){
    //方法内部进行重试
        int no = count.addAndGet(1);
        try{
            if(no<=max){
                rpc();
            }
        }catch (Exception e){
            System.out.println(e.getMessage());
            long s = no*1000;
            System.out.println("retry:"+no+" ,sleep "+s+" ms");
            busi();
        }
    }

    //max 重试次数,可以是环境变量,可以是注解的参数,可以是apollo配置==
    private static int max = 3;
    private static AtomicInteger count = new AtomicInteger(0);

    public static void main(String[] args) {
        //1.主业务方法调用busi()方法,busi()内部调用rpc远程方法,完成重试,重试次数可配
        busi();
    }
}

你可能感兴趣的:(随笔:模拟rpc远程调用失败的重试)