SpringCloud-18-OpenFeign超时控制和日志增强

32 篇文章 1 订阅
2 篇文章 0 订阅
7.6 OpenFeign 超时控制
  • OpenFeign 客户端的默认超时时间为 1 秒钟,如果服务端处理请求的时间超过 1 秒就会报错。为了避免这样的情况,我们需要对 OpenFeign 客户端的超时时间进行控制。
  • 接着我们测试下新版的OpenFeign 是否还有超时控制。在所有的服务提供者(服务端)的 DeptController 中添加一个响应时间为 5秒的服务,代码如下
@Value("${server.port}")
private String serverPort;
@Autowired
Environment environment;

//超时测试,该服务的响应时间为 5 秒
@GetMapping("/testTimeOut")
public String testTimeOut(){
    //休眠3秒
    try {
        TimeUnit.SECONDS.sleep(5);
        //Thread.sleep(5000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    //当Application.yml中没有配置当前端口号,只能使用此方式获取端口
    serverPort = environment.getProperty("server.port");
    return serverPort;
}
  • SpringBoot获取当前服务端口有3种

1.通过注解@LocalServerPort 新版SpringBoot已过时

@LocalServerPort
private int port

2.通过注解@Value(“${server.port}”)

@Value("${server.port}")
private String serverPort;

3.通过 Environment 获取

@Autowired
Environment environment;
serverPort = environment.getProperty("server.port");
  • 在 microservice-cloud-consumer-dept-openFeign 的 DeptOpenFeignService接口中添加以下代码,绑定服务端刚刚添加的超时服务。
@GetMapping("/dept/testTimeOut")
String testTimeOut();
  • 在 microservice-cloud-consumer-dept-openFeign 的 DeptConsumerController 添加以下代码来提供服务。
@GetMapping("/consumer/dept/testTimeOut")
String testTimeOut(){
    return deptOpenFeignService.testTimeOut();
}
  • 重启所有服务提供者,使用浏览器依次访问http://127.0.0.1:800X/dept/testTimeOut的服务确保所有服务提供者提供的超时服务都能正常使用,而且是6秒后显示结果。如下图。
    在这里插入图片描述
    在这里插入图片描述

  • 多次点击链接时,数据会在三个服务间轮询,并在6秒内显示结果,说明新版的OpenFeign 没有超时控制

  • 重启microservice-cloud-consumer-dept-openFeign,浏览器访问“http://localhost/consumer/dept/testTimeOut”,若客户端控制台出现超时错误。

  • 需要在配置文件中application.yml 中添加以下配置,将超时时间设置为 6 秒。

feign:
  client:
    config:
      feignServer:  #当前服务名
        connectTimeout: 6000
        readTimeout: 6000
ribbon:
  eager-load:
    enabled: true  #关闭懒加载
  # 指的是建立连接后从服务器读取到可用资源所用的时间
  ReadTimeout: 6000
  # 指的是建立连接所用的时间,适用于网络状态正常的情况下,两端连接所用的时间
  ConnectTimeout: 6000

若只配置openfeign 配置超时时间可能会不生效,因为openfeign 底层还是用的ribbon机制的超时时间的,所以无论open feign配置了多长时间超时,都永远只是默认的1秒超时。feign的配置可以翻阅源码类FeignClientProperties

7.7 OpenFeign 日志增强
  • OpenFeign 提供了日志打印功能,我们可以通过配置调整日志级别,Feign 为每一个 FeignClient 都提供了一个 feign.Logger 实例,通过它可以对 OpenFeign 服务绑定接口的调用情况进行监控。
  • configuration是配置Feign配置类,在配置类中可以自定义Feign的Encoder、Decoder、LogLevel、Contract等。
  • OpenFeign 日志打印功能的开启方式比较简单,
  • 需要在配置文件中application.yml 中添加以下配置日志等级和日志使用范围
logging:
  level:
    com:
      example:
        service: debug

以上配置说明如下:

  • com.example.service 是配置部分路径,表示监控该路径下的所有服务绑定接口,也可以配置 @FeignClient 注解的接口(即服务绑定接口)的完整类名。
  • debug:表示监听该接口的日志级别。
  • 在 com.example.config包下创建一个名为 FeignConfiguration的配置类,代码如下。
package com.example.config;



/*import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.RandomRule;*/
import feign.Logger;
import org.springframework.boot.web.embedded.jetty.JettyServletWebServerFactory;
import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.web.client.RestTemplate;

// 不要添加@Configuration,不然会被作为全局配置文件共享
public class FeignConfiguration {
    /**
     * OpenFeign 日志增强
     * 配置 OpenFeign 记录哪些内容
     */
    @Bean
    public Logger.Level feginLoggerLevel(){
        return Logger.Level.FULL;
    }

    // Contract,feignDecoder,feignEncoder.....
}
  • 该配置的作用是通过配置的 Logger.Level 对象告诉 OpenFeign 记录哪些日志内容。
  • Logger.Level 的具体级别如下:

NONE:不记录任何信息。

BASIC:仅记录请求方法、URL 以及响应状态码和执行时间。

HEADERS:除了记录 BASIC 级别的信息外,还会记录请求和响应的头信息。

FULL:记录所有请求与响应的明细,包括头信息、请求体、元数据等等。

  • 在 @FeignClient 注解的接口(即服务绑定接口)中配置@FeignClient注解的属性configuration为刚刚的自定义Feign配置类
package com.example.service;

import com.example.config.FeignConfiguration;
import com.zk.springcloud.entity.Dept;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Service添加为容器内的一个组件
 * @FeignClient value服务提供者提供的服务名称,即 application.name
 */
@Service
@FeignClient(value = "MICROSERVICECLOUDPROVIDERDEPT",configuration = FeignConfiguration.class)
public interface DeptOpenFeignService {

    //对应服务提供者(8001、8002、8003)Controller 中定义的方法
    @PostMapping("/dept/add")  //GET跟安不安全没关系的,RESTful规范问题
    boolean addDept(@RequestBody Dept dept);

    @GetMapping("/dept/get/{deptNo}")
    Dept getDeptByID(@PathVariable("deptNo") Integer deptNo);

    @GetMapping("/dept/list")
    List<Dept> queryAll();

    //对于注册进eureka里面的微服务,可以通过服务发现来获得该服务的信息
    @RequestMapping("/dept/discoveryServiceInfo")
    Object discoveryServiceInfo();

    @GetMapping("/dept/testTimeOut")
    String testTimeOut();
}
  • 重启microservice-cloud-consumer-dept-openFeign,浏览器访问“http://localhost/consumer/dept/list”,控制台输出如下。
2022-09-16 21:26:12.232  INFO 22392 --- [  restartedMain] o.s.b.web.embedded.jetty.JettyWebServer  : Jetty started on port(s) 80 (http/1.1) with context path '/'
2022-09-16 21:26:12.233  INFO 22392 --- [  restartedMain] .s.c.n.e.s.EurekaAutoServiceRegistration : Updating port to 80
2022-09-16 21:26:12.461  INFO 22392 --- [  restartedMain] iceCloudConsumerDeptOpenFeignApplication : Started MicroserviceCloudConsumerDeptOpenFeignApplication in 3.416 seconds (JVM running for 4.199)
2022-09-16 21:26:17.166 DEBUG 22392 --- [qtp545083424-61] c.example.service.DeptOpenFeignService   : [DeptOpenFeignService#queryAll] ---> GET http://MICROSERVICECLOUDPROVIDERDEPT/dept/list HTTP/1.1
2022-09-16 21:26:17.166 DEBUG 22392 --- [qtp545083424-61] c.example.service.DeptOpenFeignService   : [DeptOpenFeignService#queryAll] ---> END HTTP (0-byte body)
2022-09-16 21:26:17.272 DEBUG 22392 --- [qtp545083424-61] c.example.service.DeptOpenFeignService   : [DeptOpenFeignService#queryAll] <--- HTTP/1.1 200 OK (105ms)
2022-09-16 21:26:17.272 DEBUG 22392 --- [qtp545083424-61] c.example.service.DeptOpenFeignService   : [DeptOpenFeignService#queryAll] content-type: application/json
2022-09-16 21:26:17.272 DEBUG 22392 --- [qtp545083424-61] c.example.service.DeptOpenFeignService   : [DeptOpenFeignService#queryAll] date: Fri, 16 Sep 2022 13:26:17 GMT
2022-09-16 21:26:17.272 DEBUG 22392 --- [qtp545083424-61] c.example.service.DeptOpenFeignService   : [DeptOpenFeignService#queryAll] transfer-encoding: chunked
2022-09-16 21:26:17.272 DEBUG 22392 --- [qtp545083424-61] c.example.service.DeptOpenFeignService   : [DeptOpenFeignService#queryAll] 
2022-09-16 21:26:17.274 DEBUG 22392 --- [qtp545083424-61] c.example.service.DeptOpenFeignService   : [DeptOpenFeignService#queryAll] [{"deptNo":1,"deptName":"开发部","dbSource":"springcloud_db_core"},{"deptNo":2,"deptName":"人事部","dbSource":"springcloud_db_core"},{"deptNo":3,"deptName":"财务部","dbSource":"springcloud_db_core"},{"deptNo":4,"deptName":"市场部","dbSource":"springcloud_db_core"},{"deptNo":5,"deptName":"运维部","dbSource":"springcloud_db_core"},{"deptNo":6,"deptName":"销售部","dbSource":"springcloud_db_core"}]
2022-09-16 21:26:17.274 DEBUG 22392 --- [qtp545083424-61] c.example.service.DeptOpenFeignService   : [DeptOpenFeignService#queryAll] <--- END HTTP (415-byte body)
下一篇:SpringCloud-19-Spring Cloud Hystrix介绍和服务端降级
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值