IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> Java知识库 -> Feign和restTemplate 单个接口超时拦截处理 -> 正文阅读

[Java知识库]Feign和restTemplate 单个接口超时拦截处理


以5s超时为例。超时的接口数据,就不要了,默认为空

1. Feign超时

feign:
  client:
    config:
      default:   #default默认为所有feign的超时配置如下,可以改为具体的feign服务名
        connectTimeout: 1000 #单位毫秒
        readTimeout: 1000 #单位毫秒

2. restTemplate超时(全局)

重写以下内容

@Configuration
public class HttpConfig {
    @Bean
    public RestTemplate restTemplate() {
        //设置超时时间
        HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();
        httpRequestFactory.setConnectionRequestTimeout(10000);
        /** 连接超时参数 ConnectTimeout,让用户配置建连阶段的最长等待时间 **/
        httpRequestFactory.setConnectTimeout(10000);
        /** 读取超时参数 ReadTimeout,用来控制从 Socket 上读取数据的最长等待时间 5s**/
        httpRequestFactory.setReadTimeout(5000);
        RestTemplate restTemplate = new RestTemplate(httpRequestFactory);
        //设置UTF-8 编码
        restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
        restTemplate.getInterceptors().add(new LoggingClientHttpRequestInterceptor());
        return restTemplate;
    }
}

3. restTemplate超时(指定接口,用注解实现切面拦截)

note
当全局和指定接口的restTemplate都有时,有以下几种情况(全局超时时间:T1,指定接口超时时间:T2)
1)T1 ≥ T2:接口到达T2就会抛出
2)T1 < T2:接口到达T1就会抛出

1.定义注解

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface TargetHttpTimeout {
    /**
     * 读取超时时间,默认:-1
     */
    int timeout() default -1;
}

2.切面拦截

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;

import static org.springframework.http.HttpStatus.OK;

/**
 * @author huangying03
 * @date 2022/12/21 19:14
 */
@Slf4j
@Aspect
@Component
public class TargetHttpTimeoutAspect {

    @Around("@annotation(TargetHttpTimeout)")
    public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        TargetHttpTimeout targetHttpTimeout = methodSignature.getMethod().getAnnotation(TargetHttpTimeout.class);

        // 成员内部类
        final Object[] result = {null};
        class CallableThread implements Callable<String> {
            @Override
            public String call() {
                try {
                    long start = System.currentTimeMillis();
                    result[0] = joinPoint.proceed();
                    long end = System.currentTimeMillis();
                    log.info("[TargetHttpTimeout joinPoint.proceed]耗时:{}", end - start);
                } catch (Throwable e) {
                    log.info("[TargetHttpTimeout joinPoint.proceed]异常:", e);
                }
                return OK.name();
            }
        }
        //region 开始事件
        Callable<String> callableThread = new CallableThread();
        FutureTask<String> task = new FutureTask<>(callableThread);
        // 开启线程
        new Thread(task).start();
        try {
            // 如果 targetHttpTimeout.readTimeout() ms没有返回值就 抛出异常
            task.get(targetHttpTimeout.readTimeout(), TimeUnit.MILLISECONDS);
        } catch (Exception e) {
            log.info("[TargetHttpTimeout joinPoint.proceed]超时:", e);
        }
        //endregion 结束事件

        return result[0];
    }
}

3.注解使用 java实现
@TargetHttpTimeout(timeout = 200) //通过修改此处timeout时间来实现接口获取数据超时问题

@TargetHttpTimeout(timeout = 200)  //通过修改此处时间来实现读取超时问题
@Retryable(value = Exception.class, maxAttempts = 3, backoff = @Backoff(value = 500))
@Override
public ResponseEntity<String> getData(List<Long> projectIdList) {
    String projectIds= StringUtil.listToString(projectIdList, ",");
    String url = valueConfig.getOpenapiData() + "?projectIds={projectIds}";
    Map<String, Object> params = new HashMap<>();
    params.put("projectIds", projectIds);
 
    /** GET 请求参数不需要带着content-type **/
    HttpHeaders headers = new HttpHeaders();
    HttpEntity<String> httpEntity = new HttpEntity<>(null, headers);
    ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class, params);
    return exchange;
}
  Java知识库 最新文章
计算距离春节还有多长时间
系统开发系列 之WebService(spring框架+ma
springBoot+Cache(自定义有效时间配置)
SpringBoot整合mybatis实现增删改查、分页查
spring教程
SpringBoot+Vue实现美食交流网站的设计与实
虚拟机内存结构以及虚拟机中销毁和新建对象
SpringMVC---原理
小李同学: Java如何按多个字段分组
打印票据--java
上一篇文章      下一篇文章      查看所有文章
加:2022-12-25 10:52:39  更:2022-12-25 10:55:51 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年4日历 -2024/4/19 9:34:15-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码