当前位置: 首页 > news >正文

OpenFeign快速入门 替代RestTemplate

1.引入依赖

  <!--openFeign-->
  <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-openfeign</artifactId>
  </dependency>
  <!--负载均衡器-->
  <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-loadbalancer</artifactId>
  </dependency>

2.启用OpenFeign

cart-serviceCartApplication启动类上添加注解,启动OpenFeign功能

@EnableFeignClients
@MapperScan("com.hmall.cart.mapper")
@SpringBootApplication
public class CartApplication {
    public static void main(String[] args) {
        SpringApplication.run(CartApplication.class, args);
    }

    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
}

3.编写OpenFeign客户端

cart-service中,定义一个新的接口,编写Feign客户端

package com.hmall.cart.client;

import com.hmall.cart.domain.dto.ItemDTO;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@FeignClient("item-service")
public interface ItemClient {

    @GetMapping("/items")
    List<ItemDTO> queryItemByIds(@RequestParam("ids") Collection<Long> ids);
}
  • @FeignClient("item-service") :声明服务名称

  • @GetMapping :声明请求方式

  • @GetMapping("/items") :声明请求路径

  • @RequestParam("ids") Collection<Long> ids :声明请求参数

  • List<ItemDTO> :返回值类型

有了上述信息,OpenFeign就可以利用动态代理帮我们实现这个方法,并且向http://item-service/items发送一个GET请求,携带ids为请求参数,并自动将返回值处理为List<ItemDTO>

我们只需要直接调用这个方法,即可实现远程调用了。

4.使用FeignClient

在我们的service中实现微服务调用

        // 1.获取商品id
        Set<Long> itemIds = vos.stream().map(CartVO::getItemId).collect(Collectors.toSet());
        // 2.查询商品
        // List<ItemDTO> items = itemService.queryItemByIds(itemIds);
        // 2.1 根据服务名称获取实例列表
        List<ServiceInstance> instances = discoveryClient.getInstances("item-service");
        if (CollUtils.isEmpty(instances)){
            return;
        }
        //2.2 手写负载均衡,从实例列表中挑选一个实例
        ServiceInstance serviceInstance = instances.get(RandomUtil.randomInt(instances.size()));
        // 2.1.利用RestTemplate发起http请求,得到http的响应
        ResponseEntity<List<ItemDTO>> response = restTemplate.exchange(
//                "http://localhost:8081/items?ids={ids}",
                serviceInstance.getUri() + "/items?ids={ids}",
                HttpMethod.GET,
                null,
                new ParameterizedTypeReference<List<ItemDTO>>() {
                },
                Map.of("ids", CollUtil.join(itemIds, ","))
        );
        // 2.2.解析响应
        if(!response.getStatusCode().is2xxSuccessful()){
            // 查询失败,直接结束
            return;
        }
        List<ItemDTO> items = response.getBody();

上面一大串上次写的RestTemplate的代码可以直接简化为下面两句了

// 1.获取商品id
Set<Long> itemIds = vos.stream().map(CartVO::getItemId).collect(Collectors.toSet());
// 2.微服务调用
List<ItemDTO> items = itemClient.queryByIds(itemIds);

feign替我们完成了服务拉取、负载均衡、发送http请求的所有工作

相关文章:

  • springboot-阿里羚羊 服务端埋点
  • MySQL基础
  • 大屏幕适配方法之:transform:scale()
  • JS事件循环机制(event loop)之宏任务、微任务
  • 《最新出炉》系列初窥篇-Python+Playwright自动化测试-39-highlight() 方法之追踪定位
  • Redis 事务
  • LVGL圆弧、线条、图片、色环、按钮矩阵、文本区域、键盘部件
  • GeoScene产品学习视频收集
  • python系列教程224——导入只发生一次
  • 【python将字符串按‘/‘和‘\‘分割开】
  • 【DevOps】深入理解 Nginx Location 块:配置示例与应用场景详解
  • k8s node NotReady后会发生什么?
  • 【MySQL】表的增删查改
  • 探索最新潮流:AI配音技术的崛起
  • 7个常见的SQL慢查询问题及其解决方法
  • 【数据库基础】基本认识数据库--入门引导
  • 用Dockerfile和Shell脚本来部署一个Go项目
  • 15:00面试,15:08出来,面试问的有点变态。。。。
  • 《王者荣耀》4月狂揽2.34亿美元 单日流水1亿美元 全球销量第二
  • 新一代开源爬虫平台:SpiderFlow
  • 马上评丨准入壁垒越少,市场活力越足
  • 笔墨如何“构城”?上海美院城市山水晋京展出
  • 俄外长:俄将在不损害伙伴关系前提下发展对美关系
  • 中信银行一季度净利195.09亿增1.66%,不良率持平
  • 中办、国办印发《安全生产考核巡查办法》
  • 法治日报调查直播间“杀熟”乱象:熟客越买越贵,举证难维权不易