8.Cloud OpenFeign服务接口调用

1、概述

1.1、OpenFeign是什么?

  Feign是一个声名式WebService客户端,使用Feign能让编写WebService客户端更加简单。它的使用方法是定义一个服务接口然后在上面添加注解。Feign也支持可拔插式的编码器和解码器。SpringCloud对Feign进行了封装,使其支持了Spring MVC标准注解和HttpMessageConverters。Feign可以与Eureka和Ribbon组合使用以支持负载均衡。

1.2、Feign能做什么?

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

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

1.3、Feign和OpenFeign的区别?

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

  Feign已经停止维护,所以我们只需要关注OpenFeign的使用即可,我们现在学习的就是利用OpenFeign实现我们之前用的Ribbon+RestTemplate实现的功能。

2、OpenFeign使用步骤

  2.1、接口 + 注解,新建Module:cloud-consumer-feign-order80

  在微服务调用的接口上添加注解**@FeignClient**,注意OpenFeign在服务消费方使用。我们新建Module作为服务消费方服务。

  2.2、改POM,在POM中我们引入了OpenFeign的依赖以及Eureka客户端的依赖。

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

    <artifactId>cloud-consumer-feign-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-server</artifactId>
        </dependency>
        <dependency>
            <groupId>com.atguigu.springcloud</groupId>
            <artifactId>cloud-api-common</artifactId>
            <version>${project.version}</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

eureka:
  client:
    register-with-eureka: false # 客户端就不注册入服务注册中心了
    service-url:
      defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/

  由于80为服务消费方,只是调用服务提供方的服务,所以可以不讲自己注册到服务注册中心。

  2.4、主启动类:注意主启动类上需要添加 @EnableFeignClients 注解,这个注解声明80服务可以使用Feign来实现服务接口的调用。

package com.atguigu.springcloud;

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

/**
 * @create 2021-01-31 14:10
 */
@SpringBootApplication
@EnableFeignClients
public class OrderFeignMain80 {
    public static void main(String[] args) {
        SpringApplication.run(OrderFeignMain80.class, args);
    }
}

2.5、编写业务类:

  前面就提到过,在Feign的实现下,只需要创建一个接口并使用注解的方式来配置,这是什么意思呢,就是我们在服务消费方中的service中编写接口,并在该接口上使用 @FeignClient 注解,这样的话就能够实现对服务提供方的服务调用,首先我们看服务提供方中有如下的一个服务:

   /**
     * 服务提供方8001和8002中的服务
     * 根据id查询订单
     * @param id
     * @return
     */
    @GetMapping("/payment/get/{id}")
    public CommonResult getPaymentById(@PathVariable("id") Long id) {
        Payment payment = paymentService.getPaymentById(id);
        log.info("=======查询结果:" + payment);

        if (payment != null) {
            return new CommonResult(200, "查询数据库成功, 端口号:" + serverPort, payment);
        } else {
            return new CommonResult(444, "没有对应记录,查询ID:" + id, null);
        }
    }

  在服务消费方中编写如下的接口即可对服务提供方的服务进行调用:

package com.atguigu.springcloud.service;

import com.atguigu.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;

/**
 * @create 2021-01-31 14:31
 */
@Component
@FeignClient("CLOUD-PAYMENT-SERVICE")
public interface PaymentFeignService {

    @GetMapping("/payment/get/{id}")
    public CommonResult getPaymentById(@PathVariable("id") Long id);
}

  @FeignClient 注解中的value值为要调用的服务名称,也就是8001/8002服务提供方注册到Eureka注册中心的服务名,这个注解就是告诉该接口调用哪个服务,而默认OpenFeign会使用轮训的负载均衡算法来调用具体的服务实例,在这个接口中我们需要使用服务提供方服务的哪个具体方法,将该方法作为接口方法写入接口中即可。

  然后编写80服务消费方的Controller:

package com.atguigu.springcloud.controller;

import com.atguigu.springcloud.entities.CommonResult;
import com.atguigu.springcloud.entities.Payment;
import com.atguigu.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;

/**
 * @create 2021-01-31 14:41
 */
@RestController
@Slf4j
public class OrderFeignController {

    @Resource
    private PaymentFeignService paymentFeignService;

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

2.6、测试:

  我们先启动Eureka的集群注册中心,然后启动服务提供方8001/8002,再启动服务消费方80,访问http://localhost/consumer/payment/get/4,我们可以发现OpenFeign使用轮训的负载均衡算法实现了服务提供方服务接口的调用:
在这里插入图片描述
  2.6、总结:简言之就是,客户端的服务接口使用用 @FeignClient 注解根据服务名称去调用服务提供方的具体服务。
在这里插入图片描述

3、OpenFeign超时控制是什么?

  默认Feign 客户端只等待1秒钟,但是服务端处理需要超过1秒钟,导致Feign 客户端不想等待了,直接返回报错。

  为了避免这样的情况,有时候我们需要设置Feign客户端的超时控制。

  3.1、设置超时演示出错情况

  服务提供方8001故意写暂停程序,修改Controller:

@GetMapping(value = "/payment/feign/timeout")
public String paymentFeignTimeout()
{
    // 业务逻辑处理正确,但是需要耗费3秒钟
    try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) { e.printStackTrace(); }
    return serverPort;
}

  服务消费方80添加超时方法PaymentFeignService:

package com.atguigu.springcloud.service;

import com.atguigu.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;

/**
 * @create 2021-01-31 14:31
 */
@Component
@FeignClient("CLOUD-PAYMENT-SERVICE")
public interface PaymentFeignService {
    ......
    
    @GetMapping(value = "/payment/feign/timeout")
    public String paymentFeignTimeout();
    
}

  服务消费方80添加超时方法OrderFeignController:

package com.atguigu.springcloud.controller;

import com.atguigu.springcloud.entities.CommonResult;
import com.atguigu.springcloud.entities.Payment;
import com.atguigu.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;

/**
 * @create 2021-01-31 14:41
 */
@RestController
@Slf4j
public class OrderFeignController {

    @Resource
    private PaymentFeignService paymentFeignService;
    ......
    @GetMapping(value = "/consumer/payment/feign/timeout")
    public String paymentFeignTimeout(){
        //OpenFeign客户端一般默认等待一秒钟
        return  paymentFeignService.paymentFeignTimeout();
    };
     
}

  测试:http://localhost:8001/payment/feign/timeout
在这里插入图片描述
  8001服务提供者调用超过3秒才返回数据,再来看80调用8001的方法:http://localhost/consumer/payment/feign/timeout
OpenFeign 只等待1秒,超过后报错:
在这里插入图片描述
  3.2、YML文件里需要开启OpenFeign客户端超时控制
在这里插入图片描述
  openFeign 内与 ribbon 整合了,支持负载均衡,它的超时控制也由最底层的 ribbon 进行控制,yml 添加配置:

server:
  port: 80

spring:
  http:           #解决输出中文信息到页面为乱码的问题
    encoding:
      charset: UTF-8
      force: true
      enabled: true

eureka:
  client:
    register-with-eureka: false # 客户端就不注册入服务注册中心了
    service-url:
      defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/


# 设置feign客户端超时时间(OpenFeign默认支持ribbon)
ribbon:
  # 指的是建立连接所用的时间,适用于网络状态正常的情况下,两端连接所用的时间
  ReadTimeout: 5000
  # 指的是建立连接后从服务器读取到可用资源所用的时间
  ConnectTimeout: 5000

  重启80后 测试:http://localhost/consumer/payment/feign/timeout
在这里插入图片描述
  数据在3秒后返回,没有报错。

OpenFeign 默认是1秒钟,部分业务时间长了可以通过这个方法进行设置。

4、OpenFeign日志打印功能

4.1、日志功能:

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

说白了就是对接口的调用情况进行监控和输出

4.2、日志级别:

  NONE:默认的,不显示任何日志

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

  HEADERS:除了 BASIC 中定义的信息之外,还有请求和响应的头信息

  FULL:除了 HEADERS 中定义的信息之外,还有请求和响应的正文及元数据

  添加配置日志Bean

package com.atguigu.springcloud.config;

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

/**
 * @create 2021-02-02 16:34
 */
@Configuration
public class FeignConfig {
    @Bean
    Logger.Level feignLoggerLevel(){
        return Logger.Level.FULL;
    }
}

  4.3、yml 配置开启日志的Feign客户端

logging:
  level:
    #feign日志以什么级别监控哪个接口
    com.atguigu.springcloud.service.PaymentFeignService: debug

  4.4、测试:http://localhost/consumer/payment/get/4
在这里插入图片描述
  控制台输出:

2021-02-02 16:49:32.263 DEBUG 6864 --- [p-nio-80-exec-2] c.a.s.service.PaymentFeignService        : [PaymentFeignService#getPaymentById] ---> GET http://CLOUD-PAYMENT-SERVICE/payment/get/4 HTTP/1.1
2021-02-02 16:49:32.263 DEBUG 6864 --- [p-nio-80-exec-2] c.a.s.service.PaymentFeignService        : [PaymentFeignService#getPaymentById] ---> END HTTP (0-byte body)
2021-02-02 16:49:32.339 DEBUG 6864 --- [p-nio-80-exec-2] c.a.s.service.PaymentFeignService        : [PaymentFeignService#getPaymentById] <--- HTTP/1.1 200 (75ms)
2021-02-02 16:49:32.339 DEBUG 6864 --- [p-nio-80-exec-2] c.a.s.service.PaymentFeignService        : [PaymentFeignService#getPaymentById] connection: keep-alive
2021-02-02 16:49:32.339 DEBUG 6864 --- [p-nio-80-exec-2] c.a.s.service.PaymentFeignService        : [PaymentFeignService#getPaymentById] content-type: application/json;charset=UTF-8
2021-02-02 16:49:32.339 DEBUG 6864 --- [p-nio-80-exec-2] c.a.s.service.PaymentFeignService        : [PaymentFeignService#getPaymentById] date: Tue, 02 Feb 2021 08:49:32 GMT
2021-02-02 16:49:32.339 DEBUG 6864 --- [p-nio-80-exec-2] c.a.s.service.PaymentFeignService        : [PaymentFeignService#getPaymentById] keep-alive: timeout=60
2021-02-02 16:49:32.339 DEBUG 6864 --- [p-nio-80-exec-2] c.a.s.service.PaymentFeignService        : [PaymentFeignService#getPaymentById] transfer-encoding: chunked
2021-02-02 16:49:32.339 DEBUG 6864 --- [p-nio-80-exec-2] c.a.s.service.PaymentFeignService        : [PaymentFeignService#getPaymentById] 
2021-02-02 16:49:32.342 DEBUG 6864 --- [p-nio-80-exec-2] c.a.s.service.PaymentFeignService        : [PaymentFeignService#getPaymentById] {"code":200,"message":"查询成功,serverPort:8001","date":{"id":4,"serial":"guigu004"}}
2021-02-02 16:49:32.342 DEBUG 6864 --- [p-nio-80-exec-2] c.a.s.service.PaymentFeignService        : [PaymentFeignService#getPaymentById] <--- END HTTP (93-byte body)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值