Feign是一种声明式、模板化的HTTP客户端,在SpringCloud中使用Feign。可以做到使用HTTP请求远程服务时能与调用本地方法一样的编码体验,开发者完全感知不到是一个远程方法,更感知不到这是一个HTTP请求
Feign的灵感来自于Retrofit,JAXRS-2.0和WebSocket,它使得Java HTTP客户端编写更方便,旨在通过最少的资源和代码来实现和HTTP API的连接。
在需要调用HTTP api的工程加入下面依赖
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency>
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的负载均衡。
SpringCloud学习笔记(8)----Spring Cloud Netflix之声明式 REST客户端 -Feign的使用
原文:https://www.cnblogs.com/Eternally-dream/p/9845055.html