• SpringCloud(6):feign详解


    1 Feign简介

    Feign是Netflix开发的声明式、模板化的HTTP客户端, Feign可以帮助我们更快捷、优雅地调用HTTP API

    Feign是一个声明式的伪Http客户端,它使得写Http客户端变得更简单。使用Feign,只需要创建一个接口并注解。

    Feign默认集成了Ribbon,并和Eureka结合,默认实现了负载均衡的效果。

    简而言之:

    Feign 采用的是基于接口的注解

    2 RestTemplate和feign区别

    使用 RestTemplate时 ,URL参数是以编程方式构造的,数据被发送到其他服务。

    Feign是Spring Cloud Netflix库,用于在基于REST的服务调用上提供更高级别的抽象。Spring Cloud Feign在声明性原则上工作。使用Feign时,我们在客户端编写声明式REST服务接口,并使用这些接口来编写客户端程序。开发人员不用担心这个接口的实现。

    再说,就是简化了编写,RestTemplate还需要写上服务器IP这些信息等等,而FeignClient则不用。

    3 Feign使用

    SpringCloud(4):生产者和消费者注册及调用演示基础上进行修改,主要修改order-demo模块,修改如下:

    3.1 添加pom文件

    1. <dependency>
    2. <groupId>org.springframework.cloudgroupId>
    3. <artifactId>spring-cloud-starter-openfeignartifactId>
    4. dependency>

    3.2 在启动类上,添加开feign注解

    添加@EnableFeignClients注解如下:

    1. @SpringBootApplication
    2. @EnableEurekaClient
    3. @EnableFeignClients
    4. public class OrderApp {
    5. public static void main(String[] args) {
    6. SpringApplication.run(OrderApp.class, args);
    7. }
    8. @Bean
    9. @LoadBalanced
    10. RestTemplate restTemplate() {
    11. return new RestTemplate();
    12. }
    13. }

    3.3定义接口

    1. package com.study.service;
    2. import org.springframework.cloud.openfeign.FeignClient;
    3. import org.springframework.web.bind.annotation.PathVariable;
    4. import org.springframework.web.bind.annotation.RequestMapping;
    5. import org.springframework.web.bind.annotation.RequestMethod;
    6. @FeignClient(value = "study-user")
    7. public interface FeignService
    8. {
    9. @RequestMapping(value = "/user/{id}", method = RequestMethod.GET)
    10. String getUser(@PathVariable("id") int id);
    11. }

    3.4 使用feign

    修改controller,修改方案如下:

    1. package com.study.controller;
    2. import com.study.service.FeignService;
    3. import com.study.service.OrderService;
    4. import org.springframework.beans.factory.annotation.Autowired;
    5. import org.springframework.web.bind.annotation.RequestMapping;
    6. import org.springframework.web.bind.annotation.RestController;
    7. @RestController
    8. public class OrderController {
    9. @Autowired
    10. FeignService feignService;
    11. @RequestMapping("/order2")
    12. public String addOrder2(String name, int id) { // 调用用户,查询用户信息,
    13. String result = feignService.getUser(id); return "商品:" + name + ",生成订单:" + result;
    14. }
    15. }

  • 相关阅读:
    安达发|AI算法全方位打造制造业AI智能化工厂的超级大脑
    Spring全局异常处理
    Koltin协程:Flow的触发与消费
    【WINDOWS / DOS 批处理】嵌套变量如何(延迟)展开
    平安城市解决方案-最新全套文件
    数据分析-Pandas如何观测数据的中心趋势度
    JAVA:实现N Queens 皇后问题算法(附完整源码)
    播放器开发(五):视频帧处理并用SDL渲染播放
    信号隔离、电源隔离介绍
    SpringBoot 集成RabbitMQ 实现钉钉日报定时发送功能
  • 原文地址:https://blog.csdn.net/u013938578/article/details/126160672