Spring Cloud OpenFeign

147 阅读2分钟

简介

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

如何使用

添加依赖

implementation 'org.springframework.cloud:spring-cloud-starter-openfeign'

Spring Boot 应用程序添加@EnableFeignClients注解

@SpringBootApplication
@EnableFeignClients
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}

MessageClient.java

package com.f.client;

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PostMapping;

/**
 * 消息client
 */
@FeignClient(value = "message", path = "/message", fallback = MessageClient.Fallback.class)
public interface MessageClient {

    /**
     * 发送邮件
     */
    @PostMapping("/sendEmail")
    void sendEmail();

    /**
     * 发送短信
     */
    @PostMapping("/sendSms")
    void sendSms();

    @Component
    class Fallback implements MessageClient {

        @Override
        public void sendEmail() {
            System.out.println("sendEmail Fallback");
        }

        @Override
        public void sendSms() {
            System.out.println("sendSms Fallback");
        }
    }
}

添加服务发现和负载均衡

implementation 'com.alibaba.cloud:spring-cloud-starter-alibaba-nacos-discovery'
implementation 'org.springframework.cloud:spring-cloud-loadbalancer'
// 负载均衡缓存 Caffeine
implementation 'org.springframework:spring-context-support'

启用OkHttpClient

implementation 'io.github.openfeign:feign-okhttp'

feign.okhttp.enabled=true

feign:
    httpclient:
        connectionTimeout: 1500
        enabled: false
    okhttp:
        enabled: true

超时处理

我们可以在默认客户端和命名客户端上配置超时。OpenFeign 使用两个超时参数:

  • connectTimeout防止由于服务器处理时间长而阻塞调用者。
  • readTimeout从连接建立时开始应用,在返回响应时间过长时触发。
feign:
    client:
        config:
            default:
                connectTimeout: 1500
                readTimeout: 1000
                # NONE BASIC HEADERS FULL
                loggerLevel: basic

服务熔断支持sentinel

依赖

implementation 'com.alibaba.cloud:spring-cloud-starter-alibaba-sentinel'
implementation 'com.alibaba.csp:sentinel-datasource-nacos'

配置

feign:
    circuitbreaker:
        enabled: true
    sentinel:
        enabled: true

spring:
  cloud:
    sentinel:
      datasource:
        degrade:
          nacos:
            server-addr: 192.168.147.7:8848
            namespace: dev
            username: nacos
            password: nacos
            data-id: sentinel-degrade.json
            group-id: DEFAULT_GROUP
            data-type: json
            rule-type: degrade
        flow:
          nacos:
            server-addr: 192.168.147.7:8848
            namespace: dev
            username: nacos
            password: nacos
            data-id: sentinel-flow.json
            group-id: DEFAULT_GROUP
            data-type: json
            rule-type: flow
        system:
          nacos:
            server-addr: 192.168.147.7:8848
            namespace: dev
            username: nacos
            password: nacos
            data-id: sentinel-system.json
            group-id: DEFAULT_GROUP
            data-type: json
            rule-type: system

sentinel-flow.json

[
    {
        "limitApp": "default",
        "resource": "/app/version",
        "grade": 1,
        "count": 5,
        "strategy": 0,
        "controlBehavior": 0,
        "warmUpPeriodSec": 10,
        "maxQueueingTimeMs": 500,
        "clusterMode": false
    }
]

flow.png

请求gzip压缩

feign:
  compression:
    request:
      enabled: true
      mime-types: application/json
      min-request-size: 1024
    response:
      enabled: true
      mime-types: application/json
      min-request-size: 1024

项目

f-cloud