天天看点

SpringCloud09-OpenFeign服务接口调用1、概述2、OpenFeign的使用3、OpenFeign超时控制4、OpenFeign日志打印功能

1、概述

1.1 什么是OpenFeign

官网地址:https://cloud.spring.io/spring-cloud-static/Hoxton.SR1/reference/htmlsingle/#spring-cloud-openfeign

Feign是一个声明性web服务客户端。它使编写web服务客户端变得更容易。使用Feign创建一个接口并对其进行注释。它有可插入的注释支持,包括外部注释和JAX-RS注释。Feign还支持可插入的编码器和解码器。Spring Cloud增加了对Spring MVC注释的支持,以及对使用Spring Web中默认使用的httpMessageConverter的支持。Spring Cloud集成了Ribbon和Eureka以及Spring Cloud LoadBalancer,在使用Feign时提供了一个负载均衡的http客户端

他的使用方式是:定义一个服务接口,然后在上面添加注释;

总结:Feign是一个声明式的Web服务客户端,让编写Web服务客户端变得非常容易,只需 创建一个接口,并在接口上添加注解即可。

github地址:https://github.com/spring-cloud/spring-cloud-openfeign

1.2 OpenFeign能干嘛

OpenFeign是集成了Feign的,Feign旨在使编写Java Http客户端变得更加容易;

前面在使用Ribbon+RestTemplate的时候,利用RestTemplate对Http请求的封装处理,形成了一套模板化的调用方法。但是实际开发中,由于对服务依赖的调用可能不止一处,**往往一个接口会被多处调用,所以通常都会针对每个微服务自行封装一些客户端类来包装这些依赖服务的调用。**所以,Feign在此基础上做了进一步的封装,由他来帮助我们定义和实现依赖服务接口的定义。在Feign的实现下,我们只需创建一个接口并使用注解的方式来配置它(以前是Dao接口上面标注Mapper注解,现在是一个微服务接口上面标注一个Feign注解即可);即可完成对服务提供方的接口绑定,简化了使用Spring Cloud Ribbon时,自动封装服务调用客户端的开发量。

Feign集成了Ribbon,利用Ribbon维护了Payment支付服务的服务列表信息,并且通过轮询实现了客户端的负载均衡。而与Ribbon不同的是,通过Feign只需要定义服务绑定接口,且以声明式的方式,优雅而简单的实现了服务调用。

1.3 OpenFeign和Feign的区别

OpenFeign Feign
OpenFeign是SpringCloud在Feign的基础上支持了SpringMVC的注解,如@RequestMapping等。OpenFeign的@FeignClient可以解析SpringMVC的@RequestMapping注解下的接口,并通过动态代理的方式产生实现类,实现类中做负载均衡并调用其他服务。 Feign是SpringCloud组件中的一个轻量级RESTful的Http服务客户端,Feign内置了Ribbon,用来做客户端负载均衡,去调用服务注册中心的服务。Feign的使用方式是:使用Feign的注解定义接口,调用这个接口,就可以调用服务注册中心的服务。

<dependency>

<groupId>org.springframework.cloud</groupId>

<artifactId>spring-cloud-starter-openfeign</artifactId>

</dependency>

<dependency>

<groupId>org.springframework.cloud</groupId>

<artifactId>spring-cloud-starter-feign</artifactId>

</dependency>

2、OpenFeign的使用

微服务调用接口[email protected],OpenFeign是在客户端使用的

2.1 创建cloud-consumer-openfeign-order80

SpringCloud09-OpenFeign服务接口调用1、概述2、OpenFeign的使用3、OpenFeign超时控制4、OpenFeign日志打印功能

2.2 改pom

<?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>springcloud2020</artifactId>
        <groupId>com.zdw.springcloud</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>cloud-consumer-openfeign-order80</artifactId>
    <description>订单消费者之feign</description>

    <dependencies>
        <!--openfeign-->
        <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>
        </dependency>
        <dependency>
            <groupId>com.zdw.springcloud</groupId>
            <artifactId>cloud-api-common</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
        <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-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

</project>
           

2.3 写yml

server:
  port: 80
spring:
  application:
    name: cloud-consumer-openfeign-order

eureka:
  client:
    register-with-eureka: true
    fetch-registry: true
    service-url:
      # defaultZone: http://localhost:7001/eureka
      # 集群版
      defaultZone: http://eureka7001.com:7001/eureka,http://eureka7002.com:7002/eureka
           

2.4 主启动

package com.zdw.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 OrderOpenFeignMain80 {
    public static void main(String[] args) {
        SpringApplication.run(OrderOpenFeignMain80.class,args);
    }
}
           

@EnableFeignClients :开启OpenFeign的支持

2.5 业务代码

2.5.1 @FeignClient修饰业务逻辑接口

package com.zdw.springcloud.service;

import com.zdw.springcloud.entities.CommonResult;
import com.zdw.springcloud.entities.Payment;
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;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

/**
 * OpenFeign的业务逻辑接口类,里面的方法和8001的paymentController的方法以及路径都是一样的
 */
@Component
@FeignClient(name = "CLOUD-PAYMENT-SERVICE") //指定要从哪个服务调用
public interface PaymentOpenFeignService {
    @PostMapping(value = "payment/create")
    public CommonResult create(@RequestBody Payment payment);

    @GetMapping(value = "payment/get/{id}")
    public CommonResult<Payment> get(@PathVariable("id") Long id);

    @GetMapping(value = "/payment/lb")
    public String getPaymentLB();
}
           

注意:@Component 这个注解要加,要交给Spring的IOC容器管理

@FeignClient(name = “CLOUD-PAYMENT-SERVICE”) :指定要从哪个服务调用

2.5.2 controller编写

package com.zdw.springcloud.controller;

import com.zdw.springcloud.entities.CommonResult;
import com.zdw.springcloud.entities.Payment;
import com.zdw.springcloud.service.PaymentOpenFeignService;
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 OrderOpenFeignController {

    @Resource
    PaymentOpenFeignService paymentOpenFeignService;

    @GetMapping(value = "/consumer/payment/get/{id}")
    public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id) {
        log.info("===OpenFeign80服务被调用了,会去调用8001和8002的集群服务");
        return paymentOpenFeignService.get(id);
    }
}
           

2.6 测试

启动Eureka7001和7002,然后启动payment8001和8002,最后启动新创建的这个order80服务:

Feign自带负载均衡配置项,所以我们访问:http://localhost/consumer/payment/get/1 可以看到也是8001和8002交替出现,轮询的负载均衡机制已经得到了实现了。

3、OpenFeign超时控制

3.1 超时设置,故意设置超时演示出错情况

3.1.1 payment8001和payment8002的controller添加方法

在cloud-provider-payment8001和cloud-provider-payment8002的PaymentController中添加如下方法:

@GetMapping(value = "/payment/feign/timeout")
public String paymentFeignTimeout() {
    try {
        // 暂停3秒钟
        TimeUnit.SECONDS.sleep(3);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    return serverPort;
}
           

3.1.2 order80的OpenFeign接口添加方法

在cloud-consumer-openfeign-order80的PaymentOpenFeignService添加方法:

/**
     * 模拟feign超时
     */
@GetMapping(value = "/payment/feign/timeout")
String paymentFeignTimeout();
           

3.1.3 order80的controller添加方法

在cloud-consumer-openfeign-order80的OrderOpenFeignController添加方法:

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

3.2 测试

启动服务之后,浏览器访问:http://localhost/consumer/payment/feign/timeout ,会看到报错:

SpringCloud09-OpenFeign服务接口调用1、概述2、OpenFeign的使用3、OpenFeign超时控制4、OpenFeign日志打印功能

OpenFeign默认等待1秒钟,超过后报错,而我们的8001和8002是延迟了3秒。导致客户端不想等待了,直接返回报错,为了避免这样的情况,有时候我们需要设置Feign客户端的超时时间。

3.3 设置Feign客户端的超时时间

修改cloud-consumer-openfeign-order80的application.yml,添加超时设置:

server:
  port: 80
spring:
  application:
    name: cloud-consumer-openfeign-order

eureka:
  client:
    register-with-eureka: true
    fetch-registry: true
    service-url:
      # defaultZone: http://localhost:7001/eureka
      # 集群版
      defaultZone: http://eureka7001.com:7001/eureka,http://eureka7002.com:7002/eureka
      
# 设置feign客户端超时时间(OpenFeign默认支持ribbon)
ribbon:
  # 指的是建立连接所用的时间,适用于网络状态正常的情况下,两端连接所用的时间
  ReadTimeout: 5000
  # 指的是建立连接后从服务器读取到可用资源所用的时间
  ConnectTimeout: 5000

           

设置的超时时间的 5000,就是5秒。

3.4 重新测试

浏览器访问:http://localhost/consumer/payment/feign/timeout 在等待了3秒之后,成功了返回了,不会报错。

4、OpenFeign日志打印功能

4.1 概述

Feign提供了日志打印功能,我们可以通过配置来调整日志级别,从而了解Feign中Http的请求细节,说白了就是对Feign接口的调用情况进行监控和输出。

有以下日志级别:

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

4.2 配置日志Bean

在cloud-consumer-openfeign-order80中新建一个配置类:OpenFeignConfig:

package com.zdw.springcloud.config;

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

@Configuration
public class OpenFeignConfig {

    /**
     * feignClient配置日志级别
     */
    @Bean
    public Logger.Level feignLoggerLevel() {
        // 请求和响应的头信息,请求和响应的正文及元数据,注意Logger是feign.Logger
        return Logger.Level.FULL;
    }
}
           

4.3 yml中添加配置

在cloud-consumer-openfeign-order80的application.yml中,设置feign日志以什么级别监控哪个接口,logging是顶格写的。

logging:
  level:
    # 配置 feign日志以什么级别监控哪个接口
    com.zdw.springcloud.service.PaymentOpenFeignService: debug
           

4.4 测试

启动之后,浏览器访问:http://localhost/consumer/payment/feign/timeout

看到控制台的打印信息:

2020-04-26 13:21:25.116 DEBUG 19688 --- [p-nio-80-exec-1] c.z.s.service.PaymentOpenFeignService    : [PaymentOpenFeignService#paymentFeignTimeout] <--- HTTP/1.1 200 (3299ms)
2020-04-26 13:21:25.116 DEBUG 19688 --- [p-nio-80-exec-1] c.z.s.service.PaymentOpenFeignService    : [PaymentOpenFeignService#paymentFeignTimeout] connection: keep-alive
2020-04-26 13:21:25.116 DEBUG 19688 --- [p-nio-80-exec-1] c.z.s.service.PaymentOpenFeignService    : [PaymentOpenFeignService#paymentFeignTimeout] content-length: 4
2020-04-26 13:21:25.116 DEBUG 19688 --- [p-nio-80-exec-1] c.z.s.service.PaymentOpenFeignService    : [PaymentOpenFeignService#paymentFeignTimeout] content-type: text/plain;charset=UTF-8
2020-04-26 13:21:25.116 DEBUG 19688 --- [p-nio-80-exec-1] c.z.s.service.PaymentOpenFeignService    : [PaymentOpenFeignService#paymentFeignTimeout] date: Sun, 26 Apr 2020 05:21:25 GMT
2020-04-26 13:21:25.116 DEBUG 19688 --- [p-nio-80-exec-1] c.z.s.service.PaymentOpenFeignService    : [PaymentOpenFeignService#paymentFeignTimeout] keep-alive: timeout=60
2020-04-26 13:21:25.116 DEBUG 19688 --- [p-nio-80-exec-1] c.z.s.service.PaymentOpenFeignService    : [PaymentOpenFeignService#paymentFeignTimeout] 
2020-04-26 13:21:25.118 DEBUG 19688 --- [p-nio-80-exec-1] c.z.s.service.PaymentOpenFeignService    : [PaymentOpenFeignService#paymentFeignTimeout] 8001
2020-04-26 13:21:25.118 DEBUG 19688 --- [p-nio-80-exec-1] c.z.s.service.PaymentOpenFeignService    : [PaymentOpenFeignService#paymentFeignTimeout] <--- END HTTP (4-byte body)
           

继续阅读