spring cloud OpenFeign 服务接口调用

OpenFeign

feign是一个声明式WebService 客户端,使用Feign能让编写Web Service客户端更加简单。

他的使用方法是定义一个服务接口,然后在上面添加注解。Feign也支持可插拔式的编码和解码器。Spring  Cloud 对Feign进行了封装,使其支持Spring MVC 标准注解和HttpMessageConverters。Feign可以与Eureka和Ribbon组合使用以支持负载均衡。https://spring.io/projects/spring-cloud-openfeign

 Feign能干什么?

Feign使编写java Http客户端更加容易

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

Feign集成了Ribbon

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

Feign 与OpenFeign的区别?

Feign

OpenFeign

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

OpenFeign是Spring Cloud在feign的基础上支持了SpringMvc的注解,如@RequestMapping等等

OpenFeign的@FeignClient可以解析SpringMVC的@RequestMapping注解下的接口,并通过动态代理的方式产生实现类,实现类中做负载均衡并调用其他的服务

<dependency>

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

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

</ dependency >

<dependency>

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

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

</ dependency >

OpenFeign的使用步骤:

接口加注解:微服务调用接口 + @FeignClient

主启动类:添加@EnableFeignClients

OpenFeign默认的等待时间1秒钟,超时后将报错(修改Yml):

server:
  port: 80

eureka:
  client:
    register-with-eureka: true
    service-url:
     defaultZone: defaultZone:http://eureka7001.com:7001/eureka,http://eureka7002.com:7002/eureka

spring:
  application:
    name: feign-customer-order

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

配置OpenFeign的日志级别:

1:新建config配置文件

package com.dw.springcloud.config;

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

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

2:修改yml:

server:
  port: 80

eureka:
  client:
    register-with-eureka: true
    service-url:
     defaultZone: defaultZone:http://eureka7001.com:7001/eureka,http://eureka7002.com:7002/eureka

spring:
  application:
    name: feign-customer-order

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

logging:
  level:
  # feign以什么级别监控哪个接口
   com.dw.springcloud.service.PaymentFeignService: debug
原文地址:https://www.cnblogs.com/dw3306/p/12636496.html