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

posted @ 2024-11-03 14:00  xxxLin  阅读(149)  评论(0)    收藏  举报