分享免费的编程资源和教程

网站首页 > 技术教程 正文

Springboot整合spring retry重试—通用

goqiw 2024-09-25 20:13:33 技术教程 36 ℃ 0 评论

Springboot整合spring retry重试机制

1.导入springboot坐标

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.8.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

2.除必要坐标外,加入spring retry坐标

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

3.spring retry通用方法

package com.mytest.utils;


import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;

/**
 * spring retry重试机制
 */
@Component
public class SpringRetryUtils {

    @Autowired
    private InnerRetryInvoker innerRetryInvoker;

    public Object excute(Object targetObject,String methodName,Object... args){
        Method method = BeanUtils.findMethodWithMinimalParameters(targetObject.getClass(), methodName);
        Class<?> returnType = method.getReturnType();
        Object returnObj = null;
        try {
            returnObj = innerRetryInvoker.invoke(targetObject,method,returnType,args);
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return returnObj;
    }

    @Component
    public class InnerRetryInvoker{
        public InnerRetryInvoker() {
        }
        @Retryable(backoff=@Backoff(delay=300L,multiplier=1),label=“重试查询”)
        Object invoke(Object targetObject, Method method,Class<?> returnType,Object... args) throws InvocationTargetException, IllegalAccessException {
            Object invoke = method.invoke(targetObject, args);
            if(Map.class.isAssignableFrom(returnType)){
                if(CollectionUtils.isEmpty((Map<?, ?>) invoke)){
                    throw new RuntimeException("查询结果集为空!");
                }
            }else if(List.class.isAssignableFrom(returnType)){
                if(CollectionUtils.isEmpty((Map<?, ?>) invoke)){
                    throw new RuntimeException("查询结果集为空!");
                }
            }
            return invoke;
        }
    }
}

OK,搞定了!!!

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表