• Spring Cloud中OpenFeign的使用(一)


    一:OpenFeign简介

    OpenFeign是一种声明式、模板化的HTTP客户端, 在Spring Cloud中使用OpenFeign,可以做到使用HTTP请求访问远程服务,就像调用本地方法一样的,开发者完全感知不到这是在调用远程方法,更感知不到在访问HTTP请求

    OpenFeign作为Spring Cloud的子项目,将OpenFeign集成到Spring Boot应用中的方式,为微服务架构下服务之间的调用提供了解决方案。首先,利用了OpenFeign的声明式方式定义Web服务客户端;其次还更进一步,通过集成Ribbon或Eureka实现负载均衡的HTTP客户端,除了OpenFeign自身提供的标注(annotation)之外,还可以使用JAX-RS标注,或者Spring MVC标注。

    项目地址: https://github.com/spring-cloud/spring-cloud-openfeign
    开发文档: https://cloud.spring.io/spring-cloud-openfeign/reference/html/

    二:OpenFeign的使用

    1.引入OpenFeign依赖包

    打开pom.xml文件加入,如下代码:

    <dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
    </dependency>

    2.设置OpenFeign参数

    feign:
      client:
        config:
          default:
            connectTimeout: 3000
            readTimeout: 4000
            loggerLevel: full

    3、开启Feign客户端注解

    @SpringBootApplication
    @EnableFeignClients
    public class GoodsApiApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(GoodsApiApplication.class, args);
        }
    }

    4、编写控制器

    @RestController
    public class GoodsController
    {
        @Resource
        private GoodsService goodsService;
    
        @RequestMapping("/goods/list")
        public String getGoodsList()
        {
            return goodsService.getGoodsList();
        }
    }

     5、使用Feign调用服务接口

    @Component
    @FeignClient(name = "goods-service")
    public interface GoodsService
    {
        @GetMapping("/goods/list")
        String getGoodsList();
    }

    三、OpenFeign注解

    OpenFeign 有两个重要的注解 @FeignClient和@EnableFeignClients
    其中@EnableFeignClients注解用于修饰Spring Boot应用的入口类,在Spring Boot启动应用时,扫描应用中声明的Feign客户端可访问的Web服务。@FeignClient注解用于声明Feign客户端可访问的Web服务。

    @FeignClient注解的参数:

    name/value:指定FeignClient的名称,如果项目使用了Ribbon,name属性会作为微服务的名称,用于服务发现
    qualifier: 为Feign Client 新增注解@Qualifier
    url: url一般用于调试,可以手动指定@FeignClient调用的地址
    decode404:当发生http 404错误时,如果该字段位true,会调用decoder进行解码,否则抛出FeignException
    configuration: Feign配置类,可以自定义Feign的Encoder、Decoder、LogLevel、Contract
    fallback: 定义容错的处理类,当调用远程接口失败或超时时,会调用对应接口的容错逻辑,fallback指定的类必须实现@FeignClient标记的接口
    fallbackFactory: 工厂类,用于生成fallback类示例,通过这个属性我们可以实现每个接口通用的容错逻辑,减少重复的代码
    path: 定义当前FeignClient的统一前缀
    primary: 是否将此Feign代理标记为一个Primary Bean,默认为ture

    下节分享@FeignClient注解参数的具体使用

  • 相关阅读:
    关于清除浮动的最佳方法
    Bootstrap学习——栅格系统
    人工智能、机器学习和深度学习之间的区别与联系
    speech
    爬虫—启新宝接口函数
    爬虫—天眼查接口函数
    python链接mysql获得某列最大值
    获取指定路径下特定后缀的文件
    python读Excel
    DataTable 递归 简单的程序,来实现无限级列表 结合 jquery.table.js 实现
  • 原文地址:https://www.cnblogs.com/huxiaoguang/p/14732830.html
Copyright © 2020-2023  润新知