栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringCloud - 服务调用组件OpenFeign使用详解(一)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringCloud - 服务调用组件OpenFeign使用详解(一)

什么是OpenFeign?

OpenFeign是Spring Cloud生态在Feign的基础上,增加了对SpringMVC注解的支持,如@RequestMapping等等。OpenFeign的@FeignClient注解可以解析SpringMVC的@RequestMapping注解下的接⼝,并通过动态代理的⽅式产⽣实现类。
Spring Cloud F及以上以上版本,Spring Boot 2.0以上版本使用的是OpenFeign,OpenFeign如果从框架结构上看就是2019年Feign停更后出现版本。也可以说新项目使用OpenFeign,2018年以前的老项目使用的是Feign。

什么是Feign?

Feign是一个声明式HTTP客户端,使用Feign能让编写HTTP客户端更加简单。它的使用方法是定义一个服务接口然后在上面添加注解,同时Feign也支持JAX-RS标准的注解,支持可拔插式的编码器和解码器。Spring Cloud对Feign进行封装,支持了Spring MVC标准注解和HttpMessageConverters。Feign可以与Eureka和Ribbon组合使用支持负载均衡。

一句话总结:

Feign是Spring Cloud生态中一个轻量级RESTful的HTTP服务客户端,Feign内置了Ribbon来完成客户端的负载均衡,客户端通过使用Feign的注解定义的接口,来调用服务注册中心的服务。

为什么使用它?

旨在使编写JAVA HTTP客户端变得更容易。

应用场景是什么?

在微服务项目中会存在多个微服务之间互相调用的情况,那么如何才能高效便捷的进行远程服务的调用呢?Spring Cloud OpenFeign的出现有效的解决了该问题。

如何使用? 1. 业务场景描述

servicex-system模块要调用servicex-category模块提供的方法,这两个模块需要在相关的注册中心中注册,可以是NACOS或者EUREKA。

2. 服务提供方源码
// ServicexCategoryController.java 的源码如下:
@RestController
@RequestMapping("/category")
@Api(value = "类目管理", description = "提供对类目对象的增删改查")
public class ServicexCategoryController extends BaseController {
    @Autowired
    private IServicexCategoryService categoryService;

    
    @ApiOperation(value = "获取类目列表", notes = "根据不同的参数获取类目列表")
    @GetMapping("/list")
    public AjaxResult list(SysCategory category) {
        return AjaxResult.success(categoryService.selectCategoryList(category));
    }
}
3. 添加相关依赖

在服务调用方的POM.XML文件中添加如下依赖:


    
        org.springframework.cloud
        spring-cloud-starter-openfeign
    

4. 添加相关注解

在服务调用方的启动类中添加如下注解:

@EnableFeignClients // 目的是为了开启Spring Cloud Feign的支持
5. 定义接口API

在服务调用方的服务层框架中,新增调用其他模块的服务接口:

// 添加FeignClient注解,绑定服务提供者, "servicex-category" 大小写都可以。
@FeignClient("servicex-category") 
public interface RemoteServicexCategoryService {
    @GetMapping(value = "/category/list")
    public R> list(@RequestParam("category")SysCategory category);
}
6. 服务调用方的源码
// ServicexSystemController.java 的源码如下:
@RestController
@RequestMapping("/category")
@Api(value = "系统管理", description = "提供对系统核心对象的增删改查")
public class ServicexSystemController extends BaseController {
    @Autowired
    private IServicexSystemService systemService;
    // 用于调用远程服务的SERVICE
    @Autowired
    private RemoteServicexCategoryService remoteServicexCategoryService;

    
    @ApiOperation(value = "获取类目列表", notes = "根据不同的参数通过OpenFeign获取类目列表")
    @GetMapping("/feign-list")
    public AjaxResult list(SysCategory category) {
        return AjaxResult.success(remoteServicexCategoryService.list(category));
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/988595.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号