八、声明式 REST 客户端-Feign 的使用

一、 什么是 Feign?
Feign 是一种声明式、模板化的 HTTP 客户端,在 Spring Cloud 中使用 Feign,可以做到使用 HTTP请求远程服务时能与调用本地方法一样的编码体验,开发者完全感知不到这是远程方法,更感知不到这是个 HTTP 请求。
Feign 的灵感来源于 Retrofit、JAXRS-2.0 和 WebSocket,它使得 Java HTTP 客户端编写更方便,旨在通过最少的资源和代码来实现和 HTTP API 的连接。

二、 引入 jar

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

说明:里面的 jar 包含有 spring-cloud-starter-Ribbon,是基于 Ribbon 来实现的

三、 使用
1、 加入注解

@EnableFeignClients 

说明:这个是开启 Feign 注解
2、 添加 IuserBiz 接口类

package com.comsys.biz;

import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

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

    @RequestMapping(value = "/api/user/{id}", method = RequestMethod.GET) 
    String view(@PathVariable(value = "id") int id); 

}

3、方法请求

package com.comsys.controller;

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;

import com.comsys.biz.IUserBiz;

@RestController 
@RequestMapping(value = "/feign/user", method = RequestMethod.POST) 
public class FeignUserController {
    @Autowired 
    private IUserBiz userBiz; 

    @RequestMapping(value = "/{id}", method = RequestMethod.GET) 
    public String get(@PathVariable(value = "id") int id) { 
        return userBiz.view(id); 
    } 
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值