OpenFeign配置(全局异常解析、请求超时)

本文介绍了一种自定义Feign错误信息的方法,通过解析HTTP响应来生成更具描述性的异常信息,同时提供了Feign客户端和服务调用超时的配置示例。

自定义全局异常

package com.snoob.baseFeign.wConfig;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.snoob.springcloudalibaba.base.BaseFeignException;
import feign.Response;
import feign.Util;
import feign.codec.ErrorDecoder;
import feign.form.util.CharsetUtil;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.io.Reader;
import java.text.MessageFormat;

/**
 * @描述: 自定义Feign错误信息
 * @作者: lixing
 * @日期 2021/4/14 13:01
 */
@Configuration
public class FeignErrorDecoder implements ErrorDecoder {
    @Override
    public Exception decode(String methodKey, Response response) {
        Reader reader = null;
        try {
            reader = response.body().asReader(CharsetUtil.UTF_8);
            String errMsg = Util.toString(reader);
            if (errMsg.contains("Load balancer does not contain an instance for the service")) {
                // Load balancer does not contain an instance for the service serviceAdmin
                String pathTemp = errMsg.replace("Load balancer does not contain an instance for the service", "").trim();
                return new BaseFeignException(MessageFormat.format("{0}: {1}", pathTemp, errMsg));
            } else {
                JSONObject errMsgJsonObj = JSON.parseObject(errMsg);
                //            {
                //                "path": "/serviceUser/auth/login",
                //                "trace": "java.lang.ArithmeticException: / by zero\r\n\tat",
                //                "error": "Internal Server Error",
                //                "message": "/ by zero",
                //                "timestamp": "2021-06-26 21:42:49",
                //                "status": 500
                //            }
                String pathTemp = errMsgJsonObj.getString("path");
                String messageTemp = errMsgJsonObj.getString("message");
                return new BaseFeignException(MessageFormat.format("{0}: {1}", pathTemp, messageTemp));
            }
        } catch (IOException e) {
            return new BaseFeignException(MessageFormat.format("自定义Feign错误信息出错:{0}", e.getMessage()));
        } finally {
            if (null != reader) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        // return decode(methodKey, response);
    }
}

请求超时

# feign配置
feign:
  httpclient:
    enabled: true # 默认开启
  client:
    config:
      default: # 默认全局服务调用超时配置
        connectTimeout: 2000 # 连接超时
        readTimeout: 2000 # 接口请求超时
      serviceAdmin: # 自定义服务调用超时配置
        connectTimeout: 100000
        readTimeout: 100000

OkHttpClient请求超时

public static void main(String[] args) throws IOException {
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(1, TimeUnit.SECONDS)
                .readTimeout(2, TimeUnit.SECONDS)
                .build();

        Request request = new Request.Builder()
                .url("http://127.0.0.1:8888/3PL/testHttp")
                .header("token", "token_9c33f844-ffb7-4765-88ae-258624a5f526")
                .get()
                .build();
        String message = null;
        String result = null;
        try {
            Response response = client.newCall(request).execute();
            if (!response.isSuccessful()) {
                throw new RuntimeException("请求失败");
            }
            message = response.message();
            result = response.body().string();
        } catch (SocketTimeoutException socketTimeoutException) {
            if ("connect timed out".equalsIgnoreCase(socketTimeoutException.getMessage())) {
                log.info("连接超时");
            }
        } catch (InterruptedIOException interruptedException) {
            if ("Read timed out".equalsIgnoreCase(interruptedException.getCause().getMessage())) {
                log.info("响应超时");
            }
        } catch (Exception e) {
            log.info(e.getMessage());
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大能嘚吧嘚

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值