SpringCloud微服务详细笔记(二):OpenFeign

目录

1.OpenFeign

1.1快速入门

1.2连接池

1.3最佳实践

1.3.1思路分析

1.3.2抽取Feign客户端

1.3.3扫描包

1.4日志输出

1.4.1.定义日志级别

1.4.2.配置


1.OpenFeign

在之前的远程调用代码中,我们是利用Nacos实现了服务的治理,利用RestTemplate实现了服务的远程调用。但是远程调用的代码太复杂了:

其实远程调用的关键点就在于四个:
- 请求方式
- 请求路径
- 请求参数
- 返回值类型

于是引出了一个新的技术:OpenFeign,来简化远程调用的代码。

1.1快速入门

OpenFeign已经被SpringCloud自动装配,实现起来非常简单:
(1)引入依赖,包括OpenFeign和负载均衡组件SpringCloudLoadBalancer

  <!--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)在cart-serviceCartApplication启动类上添加@EnableFeignClients注解,开启OpenFeign功能
(3)新开一个client包,添加ItemClient接口,编写FeignClient客户端

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-services")
public interface ItemClient {

    @GetMapping("/items")
    List<ItemDTO> queryItemByIds(@RequestParam("ids") Collection<Long> ids);
}

这里只需要声明接口,无需实现方法。接口中的几个关键信息:
- @FeignClient("item-service") :声明服务名称
- @GetMapping("/items") :声明请求方式和路径
- @RequestParam("ids") Collection<Long> ids :声明请求参数
- List<ItemDTO> :返回值类型

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

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


(4)在cart-serviceCartServiceImpl

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值