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注解标记形参

相关推荐
serendipity_hky2 天前
【微服务 - easy视频 | day01】准备工具+gateway网关及路由至内部服务
java·微服务·架构·gateway·springcloud
装不满的克莱因瓶7 天前
【Java架构师】各个微服务之间有哪些调用方式?
java·开发语言·微服务·架构·dubbo·restful·springcloud
众俗8 天前
SpringCloudAlibaba整合开发
springcloud·alibaba
阿Y加油吧18 天前
微服务——day02
springcloud
1.01^100022 天前
[3-03-01].第07节:搭建服务 - 服务重构cloud-consumer-ocommon
springcloud
xiaodaidai丶1 个月前
Eureka的自我保护机制
云原生·eureka·springcloud
森林-1 个月前
Spring Cloud Netflix Eureka:从微服务基础到高可用集群实战
微服务·云原生·eureka·springcloud
ccccczy_1 个月前
SpringCloudGateway:像城市交通指挥系统一样的微服务网关
java·springcloud·微服务网关·api网关·springcloudgateway
iiYcyk2 个月前
Eureka与Nacos的区别-服务注册+配置管理
springcloud