OpenFeign简单使用

OpenFeign入门

什么是 OpenFeign?

OpenFeign是一个远程访问的组件,用于两个微服务之间互相访问的中间件

OpenFeign使用步骤

1.添加OpenFeign的依赖

复制代码
<!-- 加入OpenFeign的依赖 -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

2.在启动类上添加@EnableFeignClients开启OpenFeign的功能支持

3.编写OpenFeign的客户端

创建一个接口,使用@FeignClient标记,其value属性设置远程访问的服务的服务名(注册到nacos注册中心的名字),同样可以设置降级操作,防止雪崩效应,两种方法设置降级操作,返回兜底值fallback和fallbackfactory

复制代码
//指定注册到nacos注册中心的微服务名value ="spzx-product"
//设置降级操作fallbackFactory = RemoteCategoryServiceFactory.class,设置熔断工厂,返回兜底值
@FeignClient(value ="spzx-product",fallbackFactory = RemoteCategoryServiceFactory.class)
public interface RemoteCategoryService {
    @GetMapping("/category/remoteGetFirstProductCatepory/{parentId}")
    //需要在形参上指定参数的value,否则有时候远程访问会报错@PathVariable(value = "parentId")
    R<List<CategoryVo>> remoteGetFirstProductCatepory(@PathVariable(value = "parentId") Long parentId);
}

注意

远程访问时,若参数为实体类类型、map,此时以json的格式进行传输的,

因此远程访问的服务中相对应的控制器方法的参数和OpenFeign的接口中相对应的方法需要使用@RequestBody注解标记形参

相关推荐
CodeCaptain2 天前
nacos-2.3.2-OEM与nacos3.1.x的差异分析
java·经验分享·nacos·springcloud
Dragon Wu2 天前
Spring Security Oauth2.1 授权码模式实现前后端分离的方案
java·spring boot·后端·spring cloud·springboot·springcloud
七夜zippoe4 天前
分布式配置中心终极对决 Spring Cloud Config与Apollo架构深度解析
分布式·架构·springcloud·apollo·配置中心
没有bug.的程序员6 天前
Spring Cloud Alibaba:Nacos 配置中心与服务发现的工业级深度实战
java·spring boot·nacos·服务发现·springcloud·配置中心·alibaba
短剑重铸之日11 天前
《SpringCloud实用版》Stream + RocketMQ 实现可靠消息 & 事务消息
后端·rocketmq·springcloud·消息中间件·事务消息
没有bug.的程序员12 天前
Spring Cloud Stream:消息驱动微服务的实战与 Kafka 集成终极指南
java·微服务·架构·kafka·stream·springcloud·消息驱动
没有bug.的程序员13 天前
Spring Cloud Gateway:API网关限流与熔断实战
java·开发语言·数据库·spring boot·gateway·api·springcloud
wfsm17 天前
nacos和openfeign
springcloud
无心水17 天前
【分布式利器:腾讯TSF】11、腾讯TSF微服务框架深度对比:全面解析TSF vs Spring Cloud vs Dubbo vs Service Mesh
分布式·spring cloud·微服务·dubbo·springcloud·service mesh·分布式利器
sunnyday042618 天前
Spring Cloud Alibaba Sentinel 流量控制与熔断降级实战指南
spring boot·sentinel·springcloud