• springcloud feign配置及调用


    一、什么是Feign

    Feign是一种声明式、模板化的HTTP客户端(仅在Application Client中使用)。声明式调用是指,就像调用本地方法一样调用远程方法,无需感知操作远程http请求。
      Spring Cloud的声明式调用, 可以做到使用 HTTP请求远程服务时能就像调用本地方法一样的体验,开发者完全感知不到这是远程方法,更感知不到这是个HTTP请求。Feign的应用,让Spring Cloud微服务调用像Dubbo一样,Application Client直接通过接口方法调用Application Service,而不需要通过常规的RestTemplate构造请求再解析返回数据。它解决了让开发者调用远程接口就跟调用本地方法一样,无需关注与远程的交互细节,更无需关注分布式环境开发。

    二、使用Feign技术开发时的应用部署结构

    在这里插入图片描述
    1、在使用Feign技术开发Spring Cloud微服务时,需要先抽取要注册发布的2、服务标准,将这套标准通过接口的形式定义出来。
    3、在Application Service端开发中,依赖抽取的服务标准接口工程,并对接口给予实现。
    在Application Client端开发中,依赖抽取的服务标准接口工程,并应用接口信息和Feign技术,实现远程服务的调用。

    三、使用Feign实现客户端调用服务端的服务

    1、在客户端的pom文件中添加依赖:

            <!-- feign -->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-openfeign</artifactId>
                <version>2.2.2.RELEASE</version>
            </dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    2、客户端的启动类上添加注解

    @EnableFeignClients
    
    • 1

    在这里插入图片描述

    3、在客户端中编写服务端的feign接口文件,@FeignClient注解内的参数为调用服务端的服务名称

    @FeignClient("product-service")
    public interface ProductFeign {
        @GetMapping("/buyer/product/findPriceById/{id}")
        public BigDecimal findPriceById(@PathVariable("id") Integer id);
        @GetMapping("/buyer/product/findById/{id}")
        public ProductInfo findById(@PathVariable("id") Integer id);
        @PutMapping("/buyer/product/subStockById/{id}/{quantity}")
        public Boolean subStockById(@PathVariable("id") Integer id,@PathVariable("quantity") Integer quantity);
        @PutMapping("/buyer/product/addStockById/{id}/{quantity}")
        public Boolean addStockById(@PathVariable("id") Integer id,@PathVariable("quantity") Integer quantity);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    4、在客户端中就可以直接使用

        @Autowired
        private ProductFeign productFeign;
    		
    	//比如
    	//通过id查商品价格
      BigDecimal price = this.productFeign.findPriceById(productId);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    这里主要先通过 @EnableFeignClients注解开启扫描Spring Cloud Feign客户端的功能;然后又创建一个Feign的客户端接口定义。使用@FeignClient注释来指定这个接口所要调用的服务名称,接口中定义的各个函数使用SpringMVC的注释就可以来绑定服务提供方的REST接口。最后在Controller中,注入Client接口的实现,并调用hello方法来触发对服务提供方的调用。

  • 相关阅读:
    WPF 常用布局方式
    【CUDA编程】CUDA内存模型
    国考省考行测:继续讲结构分析法的分总、总分、分分、分总分、总分总的真题例题讲解,错项的特点规律
    戏说领域驱动设计(廿一)——领域服务
    Zookeeper的ZAB协议原理详解
    常用的卷积神经网络模型,卷积神经网络改进算法
    如何在JavaScript中比较日期
    如何提交高质量的Bug记录?
    spring
    jdbc依赖在各个框架的意义和发展
  • 原文地址:https://blog.csdn.net/weixin_42949480/article/details/127464078