• 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. }

  • 相关阅读:
    QAbstractScrollArea、QScrollArea
    上传ipa到appstore最简单的方法
    sourcetree 配置 gitlab ssh及公钥私钥设置
    第2章 Spring Boot实践,开发社区登录模块(下)
    Java 框架的一些文件配置
    思迈特软件蝉联IDC中国Fintech 50强,金融科技实力再获认可!
    Java面试题:为什么HashMap不建议使用对象作为Key?
    东南亚电商巨头Shopee宣布裁员,互联网大厂还能养老吗?
    微服务实战系列之SpringCloud Alibaba学习(七)
    【心理学】2022-08-08 日常生活问题回答
  • 原文地址:https://blog.csdn.net/u013938578/article/details/126160672