Java Spring - Retry 优雅重试机制

try-catch-redo简单重试模式

public void commonRetry(Map<String, Object> dataMap) throws InterruptedException {
		Map<String, Object> paramMap = Maps.newHashMap();
		paramMap.put("tableName", "creativeTable");
		paramMap.put("ds", "20160220");
		paramMap.put("dataMap", dataMap);
		boolean result = false;
		try {
			result = uploadToOdps(paramMap);
			if (!result) {
				Thread.sleep(1000);
				uploadToOdps(paramMap);  //一次重试
			}
		} catch (Exception e) {
			Thread.sleep(1000);
			uploadToOdps(paramMap);//一次重试
		}
	}

一般做处理尝试重连

while(someCondition()) {
    try{
        doSth();
        break;    
    } catch(Throwable th) {
        modifyCondition();
        wait();
    }
}
if(stillFail) {
    doSthWhenStillFail();
}

可以有如下操作

1,记录 log

2,保存至Kafka,Redis,Mysql

3,尝试重新保存3次左右

    public static void main(String[] args) {
        RetryTemplate retryTemplate = new RetryTemplate();
        SimpleRetryPolicy simpleRetryPolicy = new SimpleRetryPolicy();
        retryTemplate.setRetryPolicy(simpleRetryPolicy);
        FixedBackOffPolicy fixedBackOffPolicy = new FixedBackOffPolicy();
        fixedBackOffPolicy.setBackOffPeriod(100);
        retryTemplate.setBackOffPolicy(fixedBackOffPolicy);
        RetryCallback<Object, Exception> retryCallback = new RetryCallback<Object, Exception>() {
            @Override
            public Object doWithRetry(RetryContext context) throws Exception {
                System.out.println("do some thing..context.getRetryCount():" + context.getRetryCount());
                Exception exception = new UserFamilyAccountLogServiceImpl().reUpload(context.getRetryCount());
                if(exception == null){
                    return null;
                }
                throw exception;
            }
        };
        RecoveryCallback<Object> recoveryCallback = new RecoveryCallback<Object>() {
            @Override
            public Object recover(RetryContext context) throws Exception {
                System.out.println("退出恢复操作实例");
                return "null";
            }
        };
        try {
            retryTemplate.execute(retryCallback, recoveryCallback);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private Exception reUpload(int retryCount){
        if(retryCount == 1){
            return new RuntimeException("重试异常");
        }
        return null;
    }

4,重试之后再次判断操作 -- 一般用于连接池

 

参考博客

https://juejin.cn/post/6844903618148040712#heading-2

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值