SpringCloud学习笔记(9)----Spring Cloud Netflix之声明式 REST客户端 -Feign的使用

1. 什么是Feign?

  Feign是一种声明式、模板化的HTTP客户端,在SpringCloud中使用Feign。可以做到使用HTTP请求远程服务时能与调用本地方法一样的编码体验,开发者完全感知不到是一个远程方法,更感知不到这是一个HTTP请求

  Feign的灵感来自于Retrofit,JAXRS-2.0和WebSocket,它使得Java HTTP客户端编写更方便,旨在通过最少的资源和代码来实现和HTTP API的连接。

2. 引入依赖

  在需要调用HTTP api的工程加入下面依赖

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

3. 代码实现

  1. 在启动类上添加@EnableFeignClients注解开启Feign。

  2. 使用接口实现

 
package com.wangx.cloud.biz;

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

@FeignClient("spring-cloud-provider")
public interface IUserBiz {

    @RequestMapping(value = "/api/user/{id}")
    String getUser(@PathVariable(value = "id") Integer id);
}
 

  3. Controller中直接像调用本地方法一样调用

  

 
package com.wangx.cloud.controller;

import com.wangx.cloud.biz.IUserBiz;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping(value = "/user", method = RequestMethod.POST)
public class UserController {


    @Autowired
    private IUserBiz iUserBiz;

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public String get(@PathVariable(value = "id") int id) {
        return iUserBiz.getUser(id);
    }
}
 

  本示例是在消费者中调用消费者的服务,将会轮询的去调用消费者服务接口。

  注意:负载均衡的策略与Ribbon中的配置方式一样,因为Feign依赖Ribbon,使用的是Ribbon的负载均衡。

3. 抽取接口

  在实际的开发过程中,为了方便管理,通常是将所有的接口和bean都抽取到一个工程中,在消费者中使用的使用,只需要依赖维护接口的jar即可。跟直接在消费者中使用方式和原理一样,只是将接口和传输的实体类单独维护起来,使得开发更简单,明了。在引入的工程中需要让Spring扫描到@FeignClient注解,只需要@EnableFeignClients(basePackages = "包名")即可。

4. 参数说明

  

原文 SpringCloud学习笔记(9)----Spring Cloud Netflix之声明式 REST客户端 -Feign的使用

原文地址:https://www.cnblogs.com/xiaoshen666/p/10844181.html