SpringCloud 声明式服务调用OpenFeign Hoxton版本

Spring Cloud OpenFeign简介:Spring Cloud OpenFeign通过自动配置和Spring环境以及其他Spring编程模型习惯用法提供Spring Boot应用程序对OpenFeign的集成。而Feign是一个声明式的Web服务客户端,它使编写Web服务客户端变得更容易。使用Feign需创建一个接口并对其加上注解,它具有包括Feign注解和JAX-RS注解的可插入的注解支持。Feign还支持可插拔编码器和解码器。Spring Cloud增加了对Spring MVC注解的支持,并使用了Spring Web中默认使用的HttpMessageConverters。Spring Cloud集成了Ribbon和Eureka,在使用Feign时提供负载均衡的http客户端。OpenFeign中集成了Ribbon和Hystrix。

本文主要对Spring Cloud OpenFeign的基本使用进行简单总结,其中SpringBoot使用的2.2.2.RELEASE版本,SpringCloud使用的Hoxton.SR1版本。这里将沿用SpringCloud 服务注册与发现Eureka Hoxton版本eureka-server作为注册中心,eureka-client作为服务生产者,并通过Maven新建一个名为spring-cloud-openfeign的项目。

一、引入依赖

SpringBoot和SpringCloud依赖这里就不列出来了,还需引入以下依赖:

<!-- Spring Cloud Eureka Client 起步依赖 -->
<dependency>
	<groupId>org.springframework.cloud</groupId>
	<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<!-- Spring Cloud OpenFeign 起步依赖 -->
<dependency>
	<groupId>org.springframework.cloud</groupId>
	<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<!-- SpringRetry 重试框架依赖 -->
<dependency>
	<groupId>org.springframework.retry</groupId>
	<artifactId>spring-retry</artifactId>
</dependency>
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-web</artifactId>
</dependency>

二、主启动类

package com.rtxtitanv;

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

/**
 * @author rtxtitanv
 * @version 1.0.0
 * @name com.rtxtitanv.OpenFeignApplication
 * @description 主启动类
 * @date 2020/2/20 17:54
 */
@EnableFeignClients
@EnableEurekaClient
@SpringBootApplication
public class OpenFeignApplication {
    public static void main(String[] args) {
        SpringApplication.run(OpenFeignApplication.class, args);
    }
}

@EnableFeignClients:启用feign客户端,不配置包路径就默认扫描主启动类所在包及其子包下的@FeignClient注解,注册feign客户端。

三、编写配置文件

application.yml中进行如下配置:

server:
  port: ${PORT:9200}

spring:
  application:
    name: openfeign
  cloud:
    loadbalancer:
      retry:
        # 开启重试机制
        enabled: true

eureka:
  client:
    # 服务注册,是否将服务注册到Eureka注册中心,true:注册,false:不注册
    register-with-eureka: true
    # 服务发现,是否从Eureka注册中心获取注册信息,true:获取,false:不获取
    fetch-registry: true
    # 配置Eureka注册中心即Eureka服务端的地址,集群地址以,隔开
    service-url:
      defaultZone: http://rtxtitanv:rtxtitanv@eureka-server-01:8001/eureka/,http://rtxtitanv:rtxtitanv@eureka-server-02:8002/eureka/,http://rtxtitanv:rtxtitanv@eureka-server-03:8003/eureka/
  instance:
    # 将ip地址注册到Eureka注册中心
    prefer-ip-address: true
    # 该服务实例在注册中心的唯一实例ID,${spring.cloud.client.ip-address}获取该服务实例ip
    instance-id: ${spring.application.name}:${spring.cloud.client.ip-address}:${server.port}
    # 该服务实例向注册中心发送心跳间隔,单位秒,默认30秒
    lease-renewal-interval-in-seconds: 20
    # Eureka注册中心在删除此实例之前收到最后一次心跳后的等待时间,单位秒,默认90秒
    lease-expiration-duration-in-seconds: 60

# ribbon指定客户端配置
eureka-client:
  ribbon:
    # 指定Ribbon负载均衡策略,ribbon自带七种负载均衡策略,RoundRobinRule:轮询,RandomRule:随机
    # RetryRule:重试,WeightedResponseTimeRule:响应时间加权,BestAvailableRule:最小并发请求
    # AvailabilityFilteringRule:可用过滤,ZoneAvoidanceRule:区域权重
    NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RoundRobinRule

# ribbon全局配置
ribbon:
  # 处理请求的超时时间,单位ms,默认1000
  ReadTimeout: 3000
  # 连接建立的超时时间,单位ms,默认1000
  ConnectTimeout: 3000
  # 切换实例的最大重试次数,不包括首次调用,默认0次
  MaxAutoRetriesNextServer: 1
  # 对当前实例的最大重试次数,不包括首次调用,默认1次
  MaxAutoRetries: 1
  # 是否对所有操作请求都进行重试,true:是,false:否,只针对get请求进行重试
  # 设置为true时,如果是put或post等写操作,如果服务器接口不能保证幂等性,会产生不好的结果,所以OkToRetryOnAllOperations设置为true需慎用
  # 默认情况下,get请求无论是连接异常还是读取异常,都会进行重试,非get请求,只有连接异常时,才会进行重试
  OkToRetryOnAllOperations: false
  # 对指定Http响应码进行重试
  retryableStatusCodes: 404,500,502
  eager-load:
    # 是否开启ribbon立即加载,true:开启,false:关闭,默认false
    enabled: true
    # 指定需要立即加载的服务名,也就是你需要调用的服务,有多个则用逗号隔开
    clients: eureka-client

hystrix:
  command:
    # hystrix command参数全局配置
    default:
      execution:
        timeout:
          # 是否启用hystrix超时,true:启用,false:不启用
          enabled: true
        isolation:
          thread:
            # hystrix超时时间,需大于ribbon的超时时间,单位ms
            # hystrix超时时间需大于(MaxAutoRetries+1)(MaxAutoRetriesNextServer+1)(ConnectTimeout+ReadTimeout)
            timeoutInMilliseconds: 30000

feign:
  hystrix:
    # 是否启用hystrix,true:启动,false:停用,默认false
    enabled: true
  # GZIP压缩配置,提高通信效率
  compression:
    request:
      # 是否启用请求GZIP压缩,true:启用,false:不启用
      enabled: true
      # 压缩支持的MIME TYPE
      mime-types: text/xml,application/xml,application/json
      # 压缩数据的最小值
      min-request-size: 2048
    response:
      # 是否启用响应GZIP压缩,true:启用,false:不启用
      enabled: true
  client:
    config:
      # feign全局配置
      default:
        # 指定日志级别,none:不记录任何日志,basic:仅记录请求方法、URL、响应状态代码以及执行时间(适合生产环境)
        # headers:在basic基础上,记录请求和响应的header,full:记录请求和响应的header、body和元数据,默认none
        loggerLevel: basic
      # feign指定客户端配置,即仅对指定调用的服务生效
      eureka-client:
        loggerLevel: full

# 设置日志级别
logging:
  level:
    # 配置为声明式REST服务调用接口所在包
    com:
      rtxtitanv:
        # 这里需要配置为debug,否则feign的日志级别配置不会生效
        feignclient: debug

四、声明式服务调用接口

package com.rtxtitanv.feignclient;

import com.rtxtitanv.fallbacks.OpenFeignClientFallback;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;

/**
 * @author rtxtitanv
 * @version 1.0.0
 * @name com.rtxtitanv.feignclient.OpenFeignClient
 * @description 声明式REST服务调用接口
 * @date 2020/2/20 18:13
 */
@FeignClient(value = "eureka-client", fallback = OpenFeignClientFallback.class)
public interface OpenFeignClient {
    /**
     * 声明式REST服务调用接口方法,调用服务eureka-client的/home
     *
     * @return 调用eureka-client返回的结果
     */
    @GetMapping("/home")
    String openFeignTest();
}

@FeignClient:声明注解的接口为Feign客户端,这里简单总结一下@FeignClient的属性。
name:指定FeignClient的名称,如果使用了Ribbon,name会作为微服务名,用于服务发现。
value:和name作用一样。
url:一般用于调试,可以直接指定FeignClient调用的地址。
configuration:指定Feign的配置类,该配置类可以自定义Feign的Encoder、Decoder、LogLevel和Contract。
fallback:指定容错处理类,也叫降级类,用于调用远程接口失败或超时时才会调用的对应接口的容错处理,必须实现@FeignClient注解的接口。
fallbackFactory:指定容错处理工厂类,也叫降级工厂类,用于生成容错处理类实例,可以实现每个接口通用的容错逻辑,减少重复代码。
path:定义当前FeignClient的统一前缀,将当前FeignClient接口所有方法中@RequestMapping的value中相同部分路径配置到path中,简化@RequestMapping的写法。
qualifier:指定@Qualifier注解的值,该值是该FeignClient限定词,@Qualifier可以用该值注入FeignClient。
decode404:当发生http 404错误时,如果该属性为true,会调用decoder进行解码,否则抛出FeignException。
primary:是否将伪代理标记为主Bean,默认为true。

五、OpenFeign服务调用

Controller层:

package com.rtxtitanv.controller;

import com.rtxtitanv.service.OpenFeignService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author rtxtitanv
 * @version 1.0.0
 * @name com.rtxtitanv.controller.OpenFeignController
 * @description OpenFeignController
 * @date 2020/2/20 18:13
 */
@RestController
public class OpenFeignController {

    @Autowired
    private OpenFeignService openFeignService;

    @GetMapping("/openfeign")
    public String openFeign() {
        return openFeignService.openFeign();
    }
}

Service层:

package com.rtxtitanv.service;

/**
 * @author rtxtitanv
 * @version 1.0.0
 * @name com.rtxtitanv.service.OpenFeignService
 * @description OpenFeignService
 * @date 2020/2/20 18:14
 */
public interface OpenFeignService {
    /**
     * openfeign声明式REST服务调用测试,调用服务eureka-client的/home
     *
     * @return 调用eureka-client返回的结果
     */
    String openFeign();
}
package com.rtxtitanv.service.impl;

import com.rtxtitanv.feignclient.OpenFeignClient;
import com.rtxtitanv.service.OpenFeignService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author rtxtitanv
 * @version 1.0.0
 * @name com.rtxtitanv.service.impl.OpenFeignServiceImpl
 * @description OpenFeignService实现类
 * @date 2020/2/20 18:18
 */
@Service
public class OpenFeignServiceImpl implements OpenFeignService {

    @Resource
    private OpenFeignClient openFeignClient;

    @Override
    public String openFeign() {
        return openFeignClient.openFeignTest();
    }
}

IDEA启动eureka-server集群,eureka-client集群和openfeign,其中eureka-client共3个节点,然后不断访问http://localhost:9200/openfeign,这里负载均衡策略设置的轮询策略,根据下面动图中的测试过程和结果,说明以轮询的方式调用eureka-client成功,即成功完成调用eureka-client并使用Ribbon实现负载均衡,负载均衡策略为轮询策略。
测试服务调用结果

六、OpenFeign超时重试

Spring Cloud OpenFeign默认使用的Ribbon实现负载均衡和重试,OpenFeign自己的超时重试机制一般用不上,并且OpenFeign自己的重试默认是关闭的,如果有特殊需求需要用到OpenFeign的重试,可以自己实现OpenFeign的Retryer,然后再注入。这里就总结一下使用Ribbon的超时重试结合Hystrix超时的配置。

先开启Hystrix,配置feign.hystrix.enabled=true,再配置spring.cloud.loadbalancer.retry.enabled=true,开启重试机制,然后配置Ribbon超时重试,以下是全局配置,如果要使用客户端配置,需加一个前缀<client>.<client>为需要调用的服务名。

  • ribbon.ReadTimeout=3000:处理请求的超时时间,单位ms,默认1000。
  • ribbon.ConnectTimeout=3000:连接建立的超时时间,单位ms,默认1000。
  • ribbon.MaxAutoRetries=1:对当前实例的最大重试次数,不包括首次调用,默认1次。
  • ribbon.MaxAutoRetriesNextServer=1:切换实例的最大重试次数,不包括首次调用,默认0次。
  • ribbon.OkToRetryOnAllOperations=false:是否对所有操作请求都进行重试,true表示是,false表示否,只针对get请求进行重试。
  • ribbon.retryableStatusCodes=404,500,502:对指定Http响应码进行重试。

然后再配置Hystrix超时,Hystrix参数配置在配置文件中分为全局配置和实例配置,以command参数为例,全局配置以hystrix.command.default开头,实例配置以hystrix.command.<commandKey>开头,其中<commandKey>默认使用Feign客户端接口中的方法名。这里采用的全局配置,Hystrix超时配置如下:

  • hystrix.command.default.execution.timeout.enable=true:是否启用hystrix超时,true为启用,false为不启用。
  • hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds=30000:hystrix超时时间。

注意:Hystrix超时时间需超过Ribbon的超时时间,否则还没达到Ribbon的超时时间,Hystrix就触发容错保护机制执行降级了,就达不到Ribbon重试的效果,而Ribbon一共请求服务的次数为(MaxAutoRetries+1)(MaxAutoRetriesNextServer+1),所以Hystrix超时时间需要超过(MaxAutoRetries+1)(MaxAutoRetriesNextServer+1)(ConnectTimeout+ReadTimeout)

OpenFeign默认用的Ribbon的重试,以上配置均在配置文件中配置了,这里在服务调用过程中停掉一个eureka-client节点,测试超时重试,测试过程和结果见下面动图:
测试超时重试结果1
这里在服务调用过程中停掉两个eureka-client节点,测试超时重试,测试过程和结果见下面动图:
测试超时重试结果2
分别将ribbon.MaxAutoRetriesNextServer=1改为0和2测试,改为0后,停掉一个eureka-client节点后不会切换节点,调用会失败,改为2后,对应的Hystrix超时时间再调大一点,停掉两个eureka-client节点后会重试切换两次节点而调用成功,笔者已经测试过了,这里就不上结果了,综合上述结果,说明OpenFeign成功使用Ribbon实现超时重试,有兴趣可以自己测试一下。

七、OpenFeign中使用Hystrix降级

OpenFeign中要使用Hystrix,需先配置feign.hystrix.enabled=true开启Hystrix,上文配置文件中已经配置了。然后在OpenFeignClient接口的@FeignClient注解上添加fallback = OpenFeignClientFallback.class指定降级类,OpenFeignClientFallback为OpenFeignClient的降级类,需要实现OpenFeignClient接口,降级类如下:

package com.rtxtitanv.fallbacks;

import com.rtxtitanv.feignclient.OpenFeignClient;
import org.springframework.stereotype.Component;

/**
 * @author rtxtitanv
 * @version 1.0.0
 * @name com.rtxtitanv.fallbacks.OpenFeignClientImpl
 * @description OpenFeignClient的降级类
 * @date 2020/2/20 18:19
 */
@Component
public class OpenFeignClientFallback implements OpenFeignClient {

    @Override
    public String openFeignTest() {
        return "home fall back";
    }
}

停掉eureka-client所有节点,测试服务降级类,根据下面动图中的测试过程和结果,说明服务调用失败时降级成功。
测试服务降级类
也可以在OpenFeignClient接口的@FeignClient注解上添加fallbackFactory = OpenFeignClientFallbackFactory.class指定降级工厂类,注意fallbackFactoryfallback不能共存,OpenFeignClientFallbackFactory为OpenFeignClient的降级工厂类,需要实现FallbackFactory<OpenFeignClient>接口,降级工厂类如下:

package com.rtxtitanv.fallbacks;

import com.rtxtitanv.feignclient.OpenFeignClient;
import feign.hystrix.FallbackFactory;
import org.springframework.stereotype.Component;

/**
 * @author rtxtitanv
 * @version 1.0.0
 * @name com.rtxtitanv.fallbacks.OpenFeignClientFallbackFactory
 * @description OpenFeignClient的降级工厂类
 * @date 2020/2/20 20:46
 */
@Component
public class OpenFeignClientFallbackFactory implements FallbackFactory<OpenFeignClient> {
    @Override
    public OpenFeignClient create(Throwable throwable) {
        return () -> "home fallback reason was: " + throwable.getMessage();
    }
}

停掉eureka-client所有节点,@FeignClient中的fallback暂时改为fallbackFactory以测试服务降级工厂类,根据下面动图中的测试过程和结果,说明服务调用失败时降级成功。
测试服务降级工厂类

八、OpenFeign日志级别

这里简单总结一下配置文件方式全局配置feign的日志级别,当然除了使用配置文件外还可以使用配置类的方式,不过配置文件方式更简单,优先级更高。这里就总结一下配置文件方式,首先,Feign的日志级别如下:

  • none:不记录任何日志(默认值)。
  • basic:仅记录请求方法、URL、响应状态代码以及执行时间(适合生产环境)。
  • headers:在basic基础上,记录请求和响应的header。
  • full:记录请求和响应的header、body和元数据。

配置文件方式局部配置

feign.client.config.服务名.loggerLevel=日志级别
logging.level.com.rtxtitanv.feignclient.OpenFeignClient=debug

com.rtxtitanv.feignclient.OpenFeignClient为FeignClient接口全限定名。

配置文件方式全局配置

feign.client.config.default.loggerLevel=日志级别
logging.level.com.rtxtitanv.feignclient=debug

com.rtxtitanv.feignclient为FeignClient接口所在包。

具体的配置上文配置文件中已经配置过了,下面是Feign服务调用时控制台打印的日志:

2020-02-22 23:17:09.784 DEBUG 1280 --- [eureka-client-4] c.rtxtitanv.feignclient.OpenFeignClient  : [OpenFeignClient#openFeignTest] ---> GET http://eureka-client/home HTTP/1.1
2020-02-22 23:17:09.784 DEBUG 1280 --- [eureka-client-4] c.rtxtitanv.feignclient.OpenFeignClient  : [OpenFeignClient#openFeignTest] Accept-Encoding: gzip
2020-02-22 23:17:09.784 DEBUG 1280 --- [eureka-client-4] c.rtxtitanv.feignclient.OpenFeignClient  : [OpenFeignClient#openFeignTest] Accept-Encoding: deflate
2020-02-22 23:17:09.784 DEBUG 1280 --- [eureka-client-4] c.rtxtitanv.feignclient.OpenFeignClient  : [OpenFeignClient#openFeignTest] ---> END HTTP (0-byte body)
2020-02-22 23:17:09.791 DEBUG 1280 --- [eureka-client-4] c.rtxtitanv.feignclient.OpenFeignClient  : [OpenFeignClient#openFeignTest] <--- HTTP/1.1 200 (6ms)
2020-02-22 23:17:09.791 DEBUG 1280 --- [eureka-client-4] c.rtxtitanv.feignclient.OpenFeignClient  : [OpenFeignClient#openFeignTest] connection: keep-alive
2020-02-22 23:17:09.792 DEBUG 1280 --- [eureka-client-4] c.rtxtitanv.feignclient.OpenFeignClient  : [OpenFeignClient#openFeignTest] content-length: 22
2020-02-22 23:17:09.792 DEBUG 1280 --- [eureka-client-4] c.rtxtitanv.feignclient.OpenFeignClient  : [OpenFeignClient#openFeignTest] content-type: text/plain;charset=UTF-8
2020-02-22 23:17:09.792 DEBUG 1280 --- [eureka-client-4] c.rtxtitanv.feignclient.OpenFeignClient  : [OpenFeignClient#openFeignTest] date: Sat, 22 Feb 2020 15:17:09 GMT
2020-02-22 23:17:09.792 DEBUG 1280 --- [eureka-client-4] c.rtxtitanv.feignclient.OpenFeignClient  : [OpenFeignClient#openFeignTest] keep-alive: timeout=60
2020-02-22 23:17:09.792 DEBUG 1280 --- [eureka-client-4] c.rtxtitanv.feignclient.OpenFeignClient  : [OpenFeignClient#openFeignTest] 
2020-02-22 23:17:09.792 DEBUG 1280 --- [eureka-client-4] c.rtxtitanv.feignclient.OpenFeignClient  : [OpenFeignClient#openFeignTest] ip:10.0.0.11,port:9001
2020-02-22 23:17:09.792 DEBUG 1280 --- [eureka-client-4] c.rtxtitanv.feignclient.OpenFeignClient  : [OpenFeignClient#openFeignTest] <--- END HTTP (22-byte body)

代码示例

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

RtxTitanV

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值