springcloud—— http调用-fegin

Posted cj_eryue

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了springcloud—— http调用-fegin相关的知识,希望对你有一定的参考价值。

一、简介

Feign能干什么

Feign旨在使编写Java Http客户端变得更容易。

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

Feign集成了Ribbon

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

Feign和OpenFeign两者区别

Feign是Spring Cloud组件中的一个轻量级RESTful的HTTP服务客户端Feign内置了Ribbon,用来做客户端负载均衡,去调用服务注册中心的服务。Feign的使用方式是:使用Feign的注解定义接口,调用这个接口,就可以调用服务注册中心的服务。

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-feign</artifactId>
</dependency>

OpenFeign是Spring Cloud在Feign的基础上支持了SpringMVC的注解,如@RequesMapping等等。OpenFeign的@Feignclient可以解析SpringMVc的@RequestMapping注解下的接口,并通过动态代理的方式产生实现类,实现类中做负载均衡并调用其他服务.

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

二、OpenFeign服务调用

1.构建消费者

新建

cloud-consumer-feign-order81
<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>
        </dependency>
        <dependency>
            <groupId>com.cjian.springloud</groupId>
            <artifactId>cloud-api-commons</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>
server:
  port: 81

spring:
  application:
    name: cloud-order-service

eureka:
  client:
    register-with-eureka: true
    etch-registry: true
    service-url:
      defaultZone: http://localhost:7001/eureka
      #defaultZone: http://eureka7001.com:7001/eureka,http://eureka7001.com:7002/eureka,http://eureka7001.com:7003/eureka

  instance:
    instance-id: feignConsumer81
    prefer-ip-address: true   #访问路径可以显示ip地址


package com.cjian.springcloud;

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

/**
 * @description:
 * @author: CJ
 * @time: 2021/9/9 10:10
 */
@SpringBootApplication
@EnableFeignClients
public class OrderFeignMain81 
    public static void main(String[] args) 
        SpringApplication.run(OrderFeignMain81.class, args);
    

 业务逻辑接口+@FeignClient配置调用provider服务

package com.cjian.springcloud.service;

import com.cjian.springcloud.bean.CommonResult;
import com.cjian.springcloud.bean.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;

/**
 * @description:
 * @author: CJ
 * @time: 2021/9/9 10:11
 */
@Component
@FeignClient(value = "CLOUD-PAYMENT-SERVICE")
public interface PaymentFeignService

    @GetMapping(value = "/payment/get/id")//与服务提供者的路径保持一致
    public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id);

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


package com.cjian.springcloud.controller;

import com.cjian.springcloud.bean.CommonResult;
import com.cjian.springcloud.bean.Payment;
import com.cjian.springcloud.service.PaymentFeignService;

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;

/**
 * @description:
 * @author: CJ
 * @time: 2021/9/9 10:11
 */
@RestController
public class OrderFeignController 
    @Resource
    private PaymentFeignService paymentFeignService;

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

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



2.测试

访问  http://localhost:81/consumer/feign/payment/get/3

 

 3.服务超时

3.1修改8001 和8002

@RestController
public class PaymentController 
    
    ...
    
    @Value("$server.port")
    private String serverPort;

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

3.2 测试

访问 http://localhost:81/consumer/feign/payment/timeout 

OpenFeign默认等待1秒钟,超过后报错

YML文件里需要开启OpenFeign客户端超时控制

# 设置 feign 客户端超时时间(OpenFeign 默认支持 ribbon)
ribbon:
  # 值的是建立连接所用的时间,使用与网络状态正常的情况,两端连接所用的时间
  ReadTimeout: 5000
  # 指的是建立连接后从服务器读取到可用资源所用的时间
  ConnectionTimeout: 5000
  ##最大自动重试次数
  maxAutoRetries: 3
  ## 换实例重试次数
  MaxAutoRetriesNextServer: 2
  #修改负载均衡方式
  NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule

这样即可再次访问成功

 4. OpenFeign日志增强

日志打印功能

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

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

日志级别

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

import feign.Logger;

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

/**
 * @description:
 * @author: CJ
 * @time: 2021/9/9 11:02
 */
@Configuration
public class FeignConfig

    @Bean
    Logger.Level feignLoggerLevel()
    
        return Logger.Level.FULL;
    

YML文件里需要开启日志的Feign客户端

logging:
  level:
    # feign日志以什么级别监控哪个接口
    com.cjian.springcloud.service.PaymentFeignService: debug
2021-09-10 15:35:36.654  INFO 24848 --- [erListUpdater-0] c.netflix.config.ChainedDynamicProperty  : Flipping property: CLOUD-PAYMENT-SERVICE.ribbon.ActiveConnectionsLimit to use NEXT property: niws.loadbalancer.availabilityFilteringRule.activeConnectionsLimit = 2147483647
2021-09-10 15:35:38.750 DEBUG 24848 --- [p-nio-81-exec-4] c.c.s.service.PaymentFeignService        : [PaymentFeignService#paymentFeignTimeout] <--- HTTP/1.1 200 (3251ms)
2021-09-10 15:35:38.751 DEBUG 24848 --- [p-nio-81-exec-4] c.c.s.service.PaymentFeignService        : [PaymentFeignService#paymentFeignTimeout] connection: keep-alive
2021-09-10 15:35:38.751 DEBUG 24848 --- [p-nio-81-exec-4] c.c.s.service.PaymentFeignService        : [PaymentFeignService#paymentFeignTimeout] content-length: 4
2021-09-10 15:35:38.751 DEBUG 24848 --- [p-nio-81-exec-4] c.c.s.service.PaymentFeignService        : [PaymentFeignService#paymentFeignTimeout] content-type: text/plain;charset=UTF-8
2021-09-10 15:35:38.751 DEBUG 24848 --- [p-nio-81-exec-4] c.c.s.service.PaymentFeignService        : [PaymentFeignService#paymentFeignTimeout] date: Fri, 10 Sep 2021 07:35:38 GMT
2021-09-10 15:35:38.751 DEBUG 24848 --- [p-nio-81-exec-4] c.c.s.service.PaymentFeignService        : [PaymentFeignService#paymentFeignTimeout] keep-alive: timeout=60
2021-09-10 15:35:38.751 DEBUG 24848 --- [p-nio-81-exec-4] c.c.s.service.PaymentFeignService        : [PaymentFeignService#paymentFeignTimeout] 
2021-09-10 15:35:38.752 DEBUG 24848 --- [p-nio-81-exec-4] c.c.s.service.PaymentFeignService        : [PaymentFeignService#paymentFeignTimeout] 8001
2021-09-10 15:35:38.752 DEBUG 24848 --- [p-nio-81-exec-4] c.c.s.service.PaymentFeignService        : [PaymentFeignService#paymentFeignTimeout] <--- END HTTP (4-byte body)

以上是关于springcloud—— http调用-fegin的主要内容,如果未能解决你的问题,请参考以下文章

springcloud 实现微服务间调用

springcloud系列四 feign远程调用服务

SpringCloud之声明式服务调用 Feign

SpringCloud Ribbon负载均衡 + OpenFeign远程HTTP调用用法与原理

SpringCloud服务调用之OpenFeign

SpringCloud服务调用之OpenFeign