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

Feign是Spring Cloud中的一种声明式HTTP客户端,简化了远程服务调用的编码体验,使其如同调用本地方法。本文介绍如何在项目中引入Feign依赖,通过示例展示如何使用FeignClient注解创建接口并实现远程服务调用。

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的使用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值