RPC远程调用组件-OpenFeign基础知识

分享

概述

OpenFeign介绍

​ OpenFeign 是⼀个声明式远程调⽤客户端,通过注解的方式可以更方便的发起远程调用,相较于编程式的RestTemplate,OpenFeign能够通过使用SpringMvc注解来声明远程调用的请求,使用了动态代理技术来封装远程服务调用的过程,并且能够与SpringCloud其他组件完美配合。

基础用法

pom依赖

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

启动类

@SpringBootApplication
@EnableFeignClients//开启OpenFeign客户端
public class Application {
    public static void main(String[] args) {
    	SpringApplication.run(Application.class, args);
    }
}

声明Feign客户端

/**
 * OpenFeign会生成StoreClient的实现,并由Spring容器进行管理
 * 使用服务名,会从注册中心获取服务实例,负载均衡调用
 */
@FeignClient("stores")
public interface StoreClient {
    @RequestMapping(method = RequestMethod.GET, value = "/stores")
    List<Store> getStores();
    
    @GetMapping("/stores")
    Page<Store> getStores(Pageable pageable);
    
    @PostMapping(value = "/stores/{storeId}", consumes = "application/json",params = "mode=upsert")
    Store update(@PathVariable("storeId") Long storeId, Store store);
    
    @DeleteMapping("/stores/{storeId:\\d+}")
    void delete(@PathVariable Long storeId);
}

三方客户端声明

/**
 * 不在相同注册中心的接口,使用url精确指明地址(域名和直接写ip都可以)
 */
@FeignClient(value = "weather-client", url = "http://aliv18.data.moji.com")
public interface WeatherFeignClient {
    
    @PostMapping("/whapi/json/alicityweather/condition")
    String getWeather(@RequestHeader("Authorization") String auth,
                      @RequestParam("token") String token,
                      @RequestParam("cityId") String cityId);
}

超时配置

spring:
  cloud:
    openfeign:
      client:
        config:
        # 客户端名称(其中default默认配置)
          default:
            logger-level: full
            connect-timeout: 1000
            read-timeout: 2000
          stores:
            logger-level: full
            connect-timeout: 3000
            read-timeout: 5000

重试配置

​ 当发生超时后,OpenFeign默认是不进行重试的。可以在yaml中进行配置,或在Spring容器中放入Retryer的实现。OpenFeign提供的重试机制可配置三个参数:

  • period:初始超时时间,控制第一次超时的时间(ms)
  • maxPeriod:最大超时时间,除第一次请求外,每次重试的超时时间为上一次请求超时时间的1.5倍,如果超过maxPeriod,则取maxPeriod
  • maxAttempts:最大重试次数

拦截器

​ OpenFeign提供了请求拦截器和响应拦截器,请求拦截器可以在发生请求前对请求进行处理。如下代码声明了一个请求拦截器,放入Spring容器的拦截器会自动生效,该拦截器在发生调用前,在请求头里添加了X-Token。

@Component
public class XTokenRequestInterceptor implements RequestInterceptor {
    
    /**
     * 请求拦截器
     * @param requestTemplate 请求模版
     **/
    @Override
    public void apply(RequestTemplate requestTemplate) {
        requestTemplate.header("X-Token", UUID.randomUUID().toString());
    }
}

兜底返回Fallback

​ 此功能需要搭配SpringCloud组件Sentinel。当请求远程服务失败,未成功获取到响应时,可通过该功能配置兜底返回逻辑。

feign:
  sentinel:
    enabled: true
@FeignClient(value = "service-product",fallback = ProductFeignClientFallback.class)
public interface ProductFeignClient {
    @GetMapping("/product/{id}")
    Product getProductById(@PathVariable("id") Long id);
}

@Component
public class ProductFeignClientFallback implements ProductFeignClient {
    @Override
    public Product getProductById(Long id) {
        System.out.println("兜底回调....");
        Product product = new Product();
        product.setId(id);
        product.setPrice(new BigDecimal("0"));
        product.setProductName("未知商品");
        product.setNum(0);
        return product;
    }
}

扩展内容

请求客户端配置

​ OpenFeign中默认使用 JDK 原生的 URLConnection 发送 HTTP 请求,我们可以集成别的组件来替换掉 URLConnection,比如 Apache HttpClient,OkHttp。

配置Apache HttpClient

​ 引入依赖。

<!-- Apache HttpClient -->
<dependency>
  <groupId>org.apache.httpcomponents</groupId>
  <artifactId>httpclient</artifactId>
  <version>4.5.7</version>
</dependency>

<!-- Feign 集成 Apache HttpClient -->
<dependency>
  <groupId>io.github.openfeign</groupId>
  <artifactId>feign-httpclient</artifactId>
  <version>10.1.0</version>
</dependency>

​ 修改yml配置,将 Feign 的 Apache HttpClient启用。

feign:
  # feign 使用 Apache HttpClient 可以忽略,默认开启
  httpclient:
    enabled: true

​ 关于配置可参考源码: org.springframework.cloud.openfeign.FeignAutoConfiguration,内部有很多@ConditionalOnProperty注解。

配置 OkHttp

​ 引入依赖。

<dependency>
  <groupId>io.github.openfeign</groupId>
  <artifactId>feign-okhttp</artifactId>
</dependency>

​ 修改yml配置,将 Feign 的 HttpClient 禁用,启用 OkHttp,配置如下:

feign:
  # 禁用默认 HttpClient
  httpclient:
    enabled: false
  # 启用 OkHttp 作为底层客户端
  okhttp:
    enabled: true

手动创建FeignClient

​ 在某些情况下,OpenFeign提供的各类配置可能无法满足你的需求,在这种情况下,你可以使用 Feign Builder API 来创建客户端。

//由Spring Cloud OpenFeign提供的默认配置
@Import(FeignClientsConfiguration.class)
class FooController {

    private FooClient fooClient;

    private FooClient adminClient;

    @Autowired
    public FooController(Client client, Encoder encoder, Decoder decoder, Contract contract, MicrometerObservationCapability micrometerObservationCapability) {
        this.fooClient = Feign.builder().client(client)
                .encoder(encoder)
                .decoder(decoder)
                .contract(contract)
                .addCapability(micrometerObservationCapability)
                .requestInterceptor(new BasicAuthRequestInterceptor("user", "user"))
                .target(FooClient.class, "https://PROD-SVC");

        this.adminClient = Feign.builder().client(client)
                .encoder(encoder)
                .decoder(decoder)
                .contract(contract)
                .addCapability(micrometerObservationCapability)
                .requestInterceptor(new BasicAuthRequestInterceptor("admin", "admin"))
                .target(FooClient.class, "https://PROD-SVC");
    }
}

SpringCache

​ 如果使用了 @EnableCaching 注解,就会创建并注册一个 CachingCapability Bean,这样你的 Feign 客户端就能识别其接口上的 @Cache* 注解。

public interface DemoClient {

    @GetMapping("/demo/{filterParam}")
    @Cacheable(cacheNames = "demo-cache", key = "#keyParam")
    String demoEndpoint(String keyParam, @PathVariable String filterParam);
}

RefreshScope

​ @RefreshScope 是 Spring Cloud 中用于动态刷新 Bean 配置的重要注解之一。它主要用来解决在 Spring Cloud 项目中通过 Spring Cloud Config 管理配置时,当外部配置发生变化时,如何实时刷新 Bean 中的配置问题。

​ 默认情况下,Feign 客户端的刷新行为处于禁用状态,需要配置开启。

spring:
  cloud:
    openfeign:
      client:
        refresh-enabled: true
@Configuration
public class FeignConfiguration {
    
    @Value("${feign.client.config.default.connectTimeout:5000}")
    private int connectTimeout;
    
    @Value("${feign.client.config.default.readTimeout:10000}")
    private int readTimeout;
    
    @Value("${feign.retry.maxAttempts:3}")
    private int maxAttempts;
    
    @Value("${feign.retry.period:1000}")
    private long period;
    
    @Bean
    @RefreshScope
    public Request.Options options() {
        return new Request.Options(connectTimeout, readTimeout);
    }
    
    @Bean
    @RefreshScope
    public Retryer retryer() {
        return new Retryer.Default(period, period * 2, maxAttempts);
    }
}

结合Apollo

@Component
public class FeignConfigChangeListener {
    
    @Autowired
    private ApplicationContext applicationContext;
    
    @ApolloConfigChangeListener("feign-config")
    private void onChange(ConfigChangeEvent changeEvent) {
        refreshFeignConfiguration();
    }
    
    private void refreshFeignConfiguration() {
        // 触发配置刷新
        RefreshScope refreshScope = applicationContext.getBean(RefreshScope.class);
        refreshScope.refreshAll();
    }
}

阅读更多

AI核心概念基础知识

本文将讲述LLM, Token, Context, Prompt, Tool, MCP, Agent, Agent Skill等AI领域核心概念。 LLM LLM(Large Language Model),即大语言模型,简称大模型,目前的大模型,基本上都是基于Transformer架构搭建的。 大模型天生就只会做一件事:根据 “已经说过的话”(包含用户的输入和模型的输出),预测「下一个词」是什么 这是一个循环往复的过程,每次输出一个Token,直到模型给出代表结束的Token Token Token = 文本经过子词分词器(Subword Tokenizer)离散化后的最小语义单元,会将用户的自然语言,进行分词,每个词会映射到一个确定的数字 模型不直接处理字符串 / 字符 / 单词,只处理Token ID(整型数字),并进行矩阵/向量运算,Token 是连接「自然语言」与「神经网络向量」

By 居居懿

列式数据库-HBase基础知识

HBase简介 HBase介绍 HBase是一个基于HDFS的分布式、面向列的开源数据库,是一个结构化数据的分布式存储系统,是当下比较火的NoSQL数据库之一。HBase使用与Google BigTable非常相识的数据模型。将用户数据存储在带标签的表中,数据行具有可排序的键和任意数量的列,该表存储稀疏,同一表中的行可以具有疯狂变化的列。HBase数据模型的关键在于稀疏、分布式、多维、排序的Key-Value结构。 如何理解稀疏?HBase的表,每行可以有不同的列,即某行该列没有数据,那么这个位置就不占用空间。 HBase逻辑结构 * Row Key:行键,Table的主键,Table中的记录默认按照行键字典序升序排列 * Column Family:列族,Table在水平方向有一个或者多个列族组成,一个列族中可以由任意多个Column组成,一个列族中的Column具有相关性,列族支持动态扩展,无需预先定义Column的数量以及类型,所有Column均以二进制格式存储,用户需要自行进行类型转换(或者说都是字符串) * Region:Hbase 表的分片,HBase

By 居居懿

流量治理组件-Sentinel基础知识

Sentinel简介 Sentinel 是面向分布式、多语言异构化服务架构的流量治理组件,主要以流量为切入点,从流量路由、流量控制、流量整形、熔断降级、系统自适应过载保护、热点流量防护等多个维度来帮助开发者保障微服务的稳定性。 微服务雪崩问题 微服务当中的调用链是极其复杂的,当微服务调用链路中的某个服务发生了故障,如果不采取措施,将引起整个链路中的所有微服务都不可用,这就是雪崩。 解决雪崩问题的常见方式: * 超时处理:设定超时时间,请求超过一定时间没有响应就返回错误信息,不会无休止等待。这样做只能“缓解”而并不能从根本上解决雪崩问题。假设这种情况:调用等待1秒超时释放一个连接,但是每1秒却进入2个及以上的连接,久而久之,总还会有雪崩的那一天(链接资源占满了)。 * 舱壁模式:限定每个业务能使用的线程数,避免耗尽整个tomcat的资源,因此也叫线程隔离。 * 熔断降级:由断路器统计业务执行的异常比例,如果超出阈值则会熔断该业务,拦截访问该业务的一切请求。 * 流量控制:限制业务访问的QPS(Queries-per-second:每秒查询率),避免服务因流量的突增而故

By 居居懿

分布式任务调度组件XXL-JOB基础知识

概述 什么是任务调度 任务调度是为了自动完成特定任务,在约定的特定时刻去执行任务的过程,比如下面的业务场景: * 某电商平台需要每天上午10点,下午3点,晚上8点发放一批优惠券 * 某财务系统需要在每天凌晨0:10分结算前一天的财务数据,统计汇总 为什么需要分布式调度 使用Spring中提供的注解@Scheduled,也能实现调度的功能。比如下面这个示例,在业务类中方法中贴上这个注解,然后在启动类上贴上@EnableScheduling注解即可。 @Scheduled(cron = "0/20 * * * * ? ") public void doWork(){ //doSomething } Spring给我们提供的这个注解可以完成任务调度的功能,但是还存在以下问题: 1. 非高可用:单机版的定式任务调度只能在一台机器上运行,如果程序或者系统出现异常就会导致功能不可用。 2. 需防止重复执行: 在单机模式下,Spring定时任务是没什么问题的。但当我们部署了一个服务的多个实例,那么这些实例都将执行定时任务的逻辑,若不进行额外的控制逻辑,将导致

By 居居懿