Spring Cloud与微服务之Feign

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ZZY1078689276/article/details/84986992

Feign简介

  Feign是Netflix开发的声明式、模板化的HTTP客户端,其灵感来自Retrofit、JAXRS-2.0以及WebSocket。Feign可以帮助我们更加便捷、优雅地调用HTTP API。

  在SpringCloud中,使用Feign非常简单——创建一个接口,并在接口上添加一些注解,代码就完成了。Feign支持多种注解,例如Feign自带的注解或者JAX-RS注解等。

  SpringCloud对Feign进行了增强,使Feign支持了SpringMVC注解,并整合了Ribbon和Eureka,从而让Feign的使用更加的方便。

Feign的使用

这里接前面的[Spring Cloud与微服务之订单微服务]。(https://blog.csdn.net/ZZY1078689276/article/details/84982360)

  添加pom.xml依赖

    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-feign</artifactId>
    </dependency>

  添加自定义的Feign接口ItemFeignClient

package com.lyc.feign;

import com.lyc.item.entity.Item;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

@FeignClient(value = "springcloud-goods-item")    //声明这是一个Feign的客户端
public interface ItemFeignClient {

    @GetMapping("/item/{id}")
    public Item queryItemById(@PathVariable("id") Long id);

}

  最后在OrderApplication中启用Feign

@EnableFeignClients

  使用的时候,直接使用Spring的@Autowired方法注入就可以了,比如说在ItemService中通过下面的方式来进行使用

@Autowired
private ItemFeignClient itemFeignClient;

Feign的使用分析

  当我们访问下面的接口时

http://127.0.0.1:8082/order/13135351635

  订单微服务会调用下面的方法:

this.itemFeignClient.queryItemById(id)

  而该方法是通过下面的方式注入的

@Autowired
private ItemFeignClient itemFeignClient;

  在ItemFeignClient中,我们指定了订单微服务将要请求的商品微服务的服务名称springcloud-goods-item以及服务的请求方式接口:

@GetMapping("/item/{id}")
public Item queryItemById(@PathVariable("id") Long id);

  而Feign就是通过在Eureka中找到springcloud-goods-item所对应的商品微服务的服务项,然后开始请求商品微服务的商品条目信息,例如可能会随机访问到下面的商品条目地址:

http://127.0.0.1:8081/item/1

  最后将查询的结果直接返回到订单微服务中。完成订单微服务对于商品微服务中的商品条目的请求操作。

猜你喜欢

转载自blog.csdn.net/ZZY1078689276/article/details/84986992