Spring cloud入门-10:服务调用-OpenFeign&feign超时控制&feign日志增强

1、OpenFeign简介

1.1 what is OpenFeign?

  访问OpenFeign的github的官方地址:https://github.com/spring-cloud/spring-cloud-openfeign。
  
  可以看到,OpenFeign是一个声明式的rest风格的客户端,使用Feign能让编写webService客户端变得更加简单。
  它的使用方法是定义一个服务接口,然后在上面添加注解。
  在这里插入图片描述

2.2 what can OpenFeign do ?

  上一篇已经介绍了基于ribbon进行负载均衡选择处理请求的服务实例,然后使用restTemplate远程调用服务来处理分布式问题了,为什么还需要OpenFeign呢?
  上一节中使用ribbon+restTemplate的方法确实可以远程调用一个服务,但是一个工程中,对服务的调用不像现在demo里只有一处调用,实际可能是很多处都在调用,所以一般都会对每个微服务封装一些客户端类来包装这些服务的调用。而这些都需要我们自己开发。
  所以,Feign在此基础上做了封装,它来帮助我们定义和实现依赖服务接口的定义。在Feign的实现下,只需创建一个接口并使用注解的方式来配置它,即可完成对服务方接口的绑定。类似于Dao接口上面标注的Mapper注解,现在是在客户端的服务接口上标注Feign注解。从而简化了使用Spring cloud Ribbon时,自己去封装调用服务的开发量

2、OpenFeign使用

2.1 建module

  这里使用的服务注册中心依然是eureka,所以我们参考cloud-consumer-order-80模块,新建一个消费订单服务模块:cloud-consumer-order-feign-80。
  在这里插入图片描述

2.2 改pom

  参考cloud-consumer-order-80模块的依赖文件,同时再新增openfeign的依赖包:spring-cloud-starter-openfeign

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>cloud2021</artifactId>
        <groupId>org.example.springcloud</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>cloud-consumer-order-feign-80</artifactId>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
        <!-- 导入 eureka client-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
            <version>2.2.2.RELEASE</version>
        </dependency>
        <!-- 导入公共包-->
        <dependency>
            <groupId>org.example.springcloud</groupId>
            <artifactId>cloud-api-commons</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
        <!-- spring boot web 依赖模块:web, actuator-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
            <version>1.14.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>

通过maven导入,可以看到openfeign依赖包内也依赖了ribbon:
在这里插入图片描述

2.3 写yml

  参考cloud-consumer-order-80模块的配置文件:

server.port=8080

spring.application.name=cloud-order-service

# 添加Eureka Client配置
# 表示是否将自己注册进Eureka Server,默认为true
eureka.client.register-with-eureka=true
# 表示是否从Eureka Server抓取已有的注册信息,默认为true。
# 该配置在单节点时无所谓,集群配置时必须设置为true,才能配合ribbon使用负载均衡
eureka.client.fetchRegistry=true
#eureka.client.service-url.defaultZone=http://localhost:7001/eureka  # 单机版
eureka.client.service-url.defaultZone=http://eureka7001.com:7001/eureka,http://eureka7002.com:7002/eureka  # 集群版

2.4 主启动

主启动类上新增@EnableFeignClients注解:
在这里插入图片描述

package com.example.springcloud;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients;

@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
public class OrderFeignMain80 {
    public static void main(String[] args) {
        SpringApplication.run(OrderFeignMain80.class, args);
    }
}

2.5 业务类

2.5.1 构建接口

  构建PaymentFeignService接口
  1、创建接口,该接口可以直接复制要调用的服务的controller的方法名和Mapping注解;
  2、在接口的上方添加注解@FeignClient,并且在value中填写待调用的服务名称;
在这里插入图片描述

package com.example.springcloud.service;

import com.example.springcloud.entities.CommonResult;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

@Component
@FeignClient(value = "cloud-payment-service")
public interface PaymentFeignService {
    @GetMapping(value = "/payment/get/{id}")
    public CommonResult getPaymentById(@PathVariable("id") Long id);
}

2.5.2 构建controller

  构建OrderFeignController:
在这里插入图片描述

package com.example.springcloud.controller;

import com.example.springcloud.entities.CommonResult;
import com.example.springcloud.service.PaymentFeignService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
@Slf4j
public class OrderFeignController {
    @Resource
    private PaymentFeignService paymentFeignService;

    @GetMapping(value = "/consumer/payment/get/{id}")
    public CommonResult getPaymentById(@PathVariable("id") Long id){
        return paymentFeignService.getPaymentById(id);
    }
}

2.6 测试

  启动eureka集群(7001,7002),启动服务提供集群(8001,8002),启动消费服务模块80。
  然后通过openfeign来调用,可以看到依然可以成功获取数据,并且由于openfign也依赖了ribbon,因此默认也是轮询调用8001,8002服务。
  在这里插入图片描述

3、OpenFeign超时控制

3.1 服务提供模块构建长时间业务处理接口

  首先在服务提供模块8001,8002构建一个服务较长时间的接口:/payment/feign/timeout
在这里插入图片描述

3.2 服务消费模块构建长时间业务处理openfeign接口

  接着在服务消费80模块构建对应的长时间业务处理openfeign接口:/payment/feign/timeout。该接口可以直接复制服务提供模块的接口即可

package com.example.springcloud.service;

import com.example.springcloud.entities.CommonResult;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

@Component
@FeignClient(value = "cloud-payment-service")
public interface PaymentFeignService {
    @GetMapping(value = "/payment/get/{id}")
    public CommonResult getPaymentById(@PathVariable("id") Long id);

    @GetMapping(value = "/payment/feign/timeout")
    public String PaymentFeignTimeout();
}

3.3 服务消费模块构建消费接口

  接着在服务消费80模块的controller构建消费接口:/consumer/payment/feign/timeout。
  由于openfeign集成了ribbon,openfeign-ribbon的客户端一般默认等待1秒钟,如果超过1秒钟则会报错。

package com.example.springcloud.controller;

import com.example.springcloud.entities.CommonResult;
import com.example.springcloud.service.PaymentFeignService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
@Slf4j
public class OrderFeignController {
    @Resource
    private PaymentFeignService paymentFeignService;

    @GetMapping(value = "/consumer/payment/get/{id}")
    public CommonResult getPaymentById(@PathVariable("id") Long id){
        return paymentFeignService.getPaymentById(id);
    }

    @GetMapping(value = "/consumer/payment/feign/timeout")
    public String PaymentFeignTimeout() {
        // openfeign-ribbon,客户端一般默认等待1秒钟
        return paymentFeignService.PaymentFeignTimeout();
    }
}

3.4 测试

  启动eureka集群7001,7002,启动服务提供者集群8001,8002,启动服务消费模块80。
首先测试8001服务的长时间业务接口:http://localhost:8001/payment/feign/timeout。
在这里插入图片描述

接着测试消费服务模块调用长时间业务处理接口:http://localhost:8080/consumer/payment/feign/timeout。可以看到由于业务处理需要3秒钟,而openfign默认等待1秒钟,因此报了超时:
  在这里插入图片描述

3.5 消费服务模块配置超时控制参数

  由于openfeign集成了ribbon进行远程调用,因此可以配置ribbon的超时控制参数,来调整openfeign接口的调用等待时间。比如刚刚设置的长时间业务处理时间是3s,这里改为将最大等待时间改为5s。
  配置参数如下:

  • ribbon.CoonecTimeout:建立连接所用的时间,适用于网络状况正常的情况下,两端连接所用的时间。
  • ribbon.ReadTimeout:建立连接后从服务器读取到可用资源所用的时间。

消费服务80模块的配置参数修改如下:

server.port=8080

spring.application.name=cloud-order-service

# 添加Eureka Client配置
# 表示是否将自己注册进Eureka Server,默认为true
eureka.client.register-with-eureka=true
# 表示是否从Eureka Server抓取已有的注册信息,默认为true。
# 该配置在单节点时无所谓,集群配置时必须设置为true,才能配合ribbon使用负载均衡
eureka.client.fetchRegistry=true
#eureka.client.service-url.defaultZone=http://localhost:7001/eureka  # 单机版
eureka.client.service-url.defaultZone=http://eureka7001.com:7001/eureka,http://eureka7002.com:7002/eureka  # 集群版

# 建立连接所用的时间,适用于网络状况正常的情况下,两端连接所用的时间
ribbon.CoonecTimeout=5000
# 建立连接后从服务器读取到可用资源所用的时间
ribbon.ReadTimeout=5000

此时再启动消费服务80模块,然后再调用长时间业务处理接口:http://localhost:8080/consumer/payment/feign/timeout。此时可以获取到接口返回数据,说明此时的等待时间已经被改为了5秒钟了。
  在这里插入图片描述

4、OpenFeign日志增强

4.1 OpenFeign日志打印

  Feign提供了日志打印功能,可以通过配置调整日志级别,从而了解Feign中Http请求的细节
  Feign提供的日志级别如下:

  • None:默认日志级别,不显示任何日志;
  • BASIC:仅记录请求方法、URL、响应状态码、执行时间。
  • HEADERS:除了BASIC中定义的信息之外,还显示请求和响应的头信息。
  • FULL:除了HEADERS中定义的信息之外,还有请求和响应的正文及元数据。

4.2 消费服务模块配置日志bean

  在消费服务80模块中添加feign日志bean,注意logger使用的是feign.Logger,我们这里开启的是日志级别中的FULL。
在这里插入图片描述

package com.example.springcloud.config;

import feign.Logger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class FeignConfig {
    @Bean
    Logger.Level feignLoggerLevel() {
        return Logger.Level.FULL;
    }
}

4.3 配置文件中开启日志的feign客户端

  在配置文件中,指定feign日志以什么级别监控哪个接口。

server.port=8080

spring.application.name=cloud-order-service

# 添加Eureka Client配置
# 表示是否将自己注册进Eureka Server,默认为true
eureka.client.register-with-eureka=true
# 表示是否从Eureka Server抓取已有的注册信息,默认为true。
# 该配置在单节点时无所谓,集群配置时必须设置为true,才能配合ribbon使用负载均衡
eureka.client.fetchRegistry=true
#eureka.client.service-url.defaultZone=http://localhost:7001/eureka  # 单机版
eureka.client.service-url.defaultZone=http://eureka7001.com:7001/eureka,http://eureka7002.com:7002/eureka  # 集群版

# 建立连接所用的时间,适用于网络状况正常的情况下,两端连接所用的时间
ribbon.CoonecTimeout=5000
# 建立连接后从服务器读取到可用资源所用的时间
ribbon.ReadTimeout=5000

# 指定feign日志以什么级别监控哪个接口
logging.level.com.example.springcloud.service.PaymentFeignService=debug

4.4 测试

配置号feign日志后,重启消费服务80模块,再次请求长时间业务处理接口:http://localhost:8080/consumer/payment/feign/timeout。可以在IDEA的日志中看到headers等信息。
在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值