SpringCloud-OpenFeign基础

2024-06-22 19:36

本文主要是介绍SpringCloud-OpenFeign基础,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

OpenFeign

OpenFeign简介

  1. OpenFeign是一个基于HTTP协议的RPC(远程过程调用)组件,用于简化HTTP请求和响应的处理。
  2. 它通过声明式的方式定义REST API接口,并自动生成实现该接口的客户端代码,从而简化了RESTful服务的调用过程。
  3. 它和其它框架,比如Dubbo、Mybatis等发送请求的框架相同,底层是动态代理
  4. 它是Feign的增强版,同时整合了Ribbon和Eureka,使Feign更加灵活

Feign.client

OpenFeign默认使用jdk的HttpUrlConnection,没有链接池,也没有资源管理,性能不是很好

Feign的日志

  1. Feign的日志级别
  2. NONE:默认的,不打印任何日志
  3. BASIC:仅记录请求方法,URL、响应状态码以及执行时间
  4. HEADERS:在BASIC基础上,记录请求和响应的header信息
  5. FULL:记录响应和请求的header、body和元数据
  6. 开发环境一般使用FULL,生产环境一般使用BASIC

配置Feign日志可以通过两种方式配置

Feign的日志打印是基于springboot日志的所以要配置springboot日志

  • 引入springboot日志依赖
        <!--日志--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-logging</artifactId></dependency>
  • 配置springboot日志输出级别
logging:level:com.shaoby: debug
  1. 配置类,需要注意的是如果使用配置类的方式,配置类加了@Configuration注解,全局使用;如果不加可以通过@FeignClient注解的configuration属性指定配置类;
public class FeignLogConfig {@Beanpublic Logger.Level logger(){return Logger.Level.FULL;}
}
@FeignClient(value = "SMS-cache",configuration = FeignLogConfig.class)
public interface SmsCacheClient {@GetMapping(value = "/cache/hGetAll/{key}")Map hGetAll(@PathVariable("key") String key);
}
  1. 配置文件,或直接使用配置文件配置feign日志
logging:level:com.shaoby: debug
feign:client:config:
#      feignClient的value,可以配置多个SMS-cache:loggerLevel: full

Feign支持的配置项

Feign契约

  1. Feign默认使用springMVC的契约,即springMVC中的注解如@RequestMapping、@PostMapper、@PathVariable等。
  2. 如果使用Feign的默认契约,就必须使用Feign中的注解调用远程接口,可通过配置文件或者配置类修改契约,默认值feign.Contract.Default
  3. 不建议修改

编解码

  1. 编解码是指的:指将请求数据编码成HTTP请求体并将HTTP响应体解码成Java对象的过程。
  2. Feign中提供了自定义编解码配置,同时也提供了多项编解码的实现,比如Gson、Jaxb、Jackson.默认使用SpringEncoder&&SpringDecoder
  3. 可通过实现Encoder&&Decoder自定义编解码
  4. 可通过配置文件指定编解码方式,一般不建议修改
feign:client:config:#调用的服务名称,可配置多个SMS-cache:encoder: com.xxx.xxxEncoderdecoder: com.xxx.xxxDecoder

拦截器

  1. 实现RequestInterceptor接口,自定义拦截器
public class FeignAuthRequestInterceptor implements RequestInterceptor {private String tookenId;public FeignAuthRequestInterceptor(String tookenId) {this.tookenId = tookenId;}@Overridepublic void apply(RequestTemplate requestTemplate) {requestTemplate.header("Authorization",tookenId);}
}
  1. 通过配置类将拦截器配置到Feign中
  2. 服务提供端加入拦截器

Client设置

Feign中默认使用JDK原生的URLConnection发送HTTP请求,可以自定义实现替换,一般使用feign自带的,比如OkHTTPClient,apche httpclient等,配置方式相同。只要引入依赖,springboot自动装配。

比如使用apche httpclient

  • 引入依赖
<dependency><groupId>io.github.openfeign</groupId><atrifactId>feign-httpclient</atrifactId>
</dependency>
  • 配置类
feign:
#  使用apche httpclienthttpclient: true
#  最大连接数max-connections: 200
#  单路径最大链接数max-connections-pre-rote: 50

超时时间配置

  • 注入配置:
@Configuration
public class FeignConfig {@Beanpublic Request.Options options(){return new Request.Options(200,400);}
}

基本使用案例

本案例基于nacos作为注册中心和配置中心,用OpenFeign实现远程过程调用。

服务提供端

  1. 引入nacos相关依赖,用于将服务注册到nacos中
<!--注册到nacos-->
<dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!--nacos拉取配置-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
  1. 配置nacos,配置注册中心地址
spring:application:name: SMS-cacheprofiles:active: devcloud:nacos:discovery:server-addr: 47.92.xxx.xxx:8848config:server-addr: 47.92.xxx.xxx:8848file-extension: ymlredis:host: 47.92.xxx.xxxport: 6379
  1. 开启nacos配置,启动类标记注解@EnableDiscoveryClient
@SpringBootApplication
@EnableDiscoveryClient
public class CacheStarterApp {public static void main(String[] args) {SpringApplication.run(CacheStarterApp.class,args);}
}
  1. 提供restful接口
/*** @Author Cookie* @Date 2024/6/22 0:42*/
@RestController
@Slf4j
public class CacheController {@Autowiredprivate RedisClient redisClient;@PostMapping(value = "/cache/hset/{key}")void hSet(@PathVariable("key") String key, @RequestBody Map map){log.info("【缓存模块】hSet方法存储数据成功key={},value{}",key,map);redisClient.putMap(key,map);}@GetMapping(value = "/cache/set/{key}/{value}")void set(@PathVariable("key") String key, @PathVariable("value") String value){log.info("【缓存模块】set方法存储数据成功key={},value{}",key,value);}
}

消费者

  1. 引入相关依赖,nacos、OpenFeign等
<!--注册到nacos--><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId></dependency><!--nacos拉取配置--><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId></dependency><!--openfeign--><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-openfeign</artifactId></dependency>
  1. 配置nacos

同被调用端,将服务注册到nacos中

  1. 标记启动类,使用@EnableFeignClients自动装配OpenFeign
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class TestAppStarter {public static void main(String[] args) {SpringApplication.run(TestAppStarter.class,args);}
}
  1. 消费者调用提供者接口,通过@FeignClient注解实现。
@FeignClient("SMS-cache")
public interface CacheClient {@PostMapping(value = "/cache/hset/{key}")void hSet(@PathVariable("key") String key, @RequestBody Map map);@GetMapping(value = "/cache/set/{key}/{value}")void set(@PathVariable("key") String key, @PathVariable("value") String value);
}

@FeignClient中有以下属性:

  1. value:指定服务的名称,要和注册中心中服务提供者名称一致
  2. name:指定该类的容器名称,即ioc中的类ID
  3. url: url一般用于调试,可以手动指定@FeignClient调用的地址
  4. decode404:当发生http 404错误时,如果该字段位true,会调用decoder进行解码,否则抛出FeignException
  5. configuration: Feign配置类,可以自定义Feign的Encoder、Decoder、LogLevel、Contract
  6. fallback: 服务容错处理类
  7. fallbackFactory: 工厂类,用于生成fallback类示例,通过这个属性我们可以实现每个接口通用的容错逻辑
  8. path: 定义当前FeignClient的统一前缀,项目中配置了server.context-path,server.servlet-path时使用
  1. 测试,注入消费者调用提供者接口的接口,由组件自动生产动态代理类
@SpringBootTest
@RunWith(SpringRunner.class)
public class ClientBusinessMapperTest {@Autowiredprivate ClientBusinessMapper mapper;@Autowiredprivate CacheClient cacheClient;@Testpublic void findById() throws JsonProcessingException {ClientBusiness clientBusiness = mapper.findById(1L);ObjectMapper objectMapper = new ObjectMapper();Map map = objectMapper.readValue(objectMapper.writeValueAsString(clientBusiness), Map.class);cacheClient.hSet("test"+clientBusiness.getApikey(),map);System.out.println("success...");}
}

这篇关于SpringCloud-OpenFeign基础的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1085215

相关文章

python panda库从基础到高级操作分析

《pythonpanda库从基础到高级操作分析》本文介绍了Pandas库的核心功能,包括处理结构化数据的Series和DataFrame数据结构,数据读取、清洗、分组聚合、合并、时间序列分析及大数据... 目录1. Pandas 概述2. 基本操作:数据读取与查看3. 索引操作:精准定位数据4. Group

Spring Boot集成/输出/日志级别控制/持久化开发实践

《SpringBoot集成/输出/日志级别控制/持久化开发实践》SpringBoot默认集成Logback,支持灵活日志级别配置(INFO/DEBUG等),输出包含时间戳、级别、类名等信息,并可通过... 目录一、日志概述1.1、Spring Boot日志简介1.2、日志框架与默认配置1.3、日志的核心作用

破茧 JDBC:MyBatis 在 Spring Boot 中的轻量实践指南

《破茧JDBC:MyBatis在SpringBoot中的轻量实践指南》MyBatis是持久层框架,简化JDBC开发,通过接口+XML/注解实现数据访问,动态代理生成实现类,支持增删改查及参数... 目录一、什么是 MyBATis二、 MyBatis 入门2.1、创建项目2.2、配置数据库连接字符串2.3、入

Springboot项目启动失败提示找不到dao类的解决

《Springboot项目启动失败提示找不到dao类的解决》SpringBoot启动失败,因ProductServiceImpl未正确注入ProductDao,原因:Dao未注册为Bean,解决:在启... 目录错误描述原因解决方法总结***************************APPLICA编

深度解析Spring Security 中的 SecurityFilterChain核心功能

《深度解析SpringSecurity中的SecurityFilterChain核心功能》SecurityFilterChain通过组件化配置、类型安全路径匹配、多链协同三大特性,重构了Spri... 目录Spring Security 中的SecurityFilterChain深度解析一、Security

SpringBoot多环境配置数据读取方式

《SpringBoot多环境配置数据读取方式》SpringBoot通过环境隔离机制,支持properties/yaml/yml多格式配置,结合@Value、Environment和@Configura... 目录一、多环境配置的核心思路二、3种配置文件格式详解2.1 properties格式(传统格式)1.

Apache Ignite 与 Spring Boot 集成详细指南

《ApacheIgnite与SpringBoot集成详细指南》ApacheIgnite官方指南详解如何通过SpringBootStarter扩展实现自动配置,支持厚/轻客户端模式,简化Ign... 目录 一、背景:为什么需要这个集成? 二、两种集成方式(对应两种客户端模型) 三、方式一:自动配置 Thick

Spring WebClient从入门到精通

《SpringWebClient从入门到精通》本文详解SpringWebClient非阻塞响应式特性及优势,涵盖核心API、实战应用与性能优化,对比RestTemplate,为微服务通信提供高效解决... 目录一、WebClient 概述1.1 为什么选择 WebClient?1.2 WebClient 与

Java.lang.InterruptedException被中止异常的原因及解决方案

《Java.lang.InterruptedException被中止异常的原因及解决方案》Java.lang.InterruptedException是线程被中断时抛出的异常,用于协作停止执行,常见于... 目录报错问题报错原因解决方法Java.lang.InterruptedException 是 Jav

深入浅出SpringBoot WebSocket构建实时应用全面指南

《深入浅出SpringBootWebSocket构建实时应用全面指南》WebSocket是一种在单个TCP连接上进行全双工通信的协议,这篇文章主要为大家详细介绍了SpringBoot如何集成WebS... 目录前言为什么需要 WebSocketWebSocket 是什么Spring Boot 如何简化 We