Feign 的目的是简化 Web Service 客户端的开发,在使用 Feign 时,使用注解来修饰接口,被注解修饰的接口具有访问 Web Service 的能力,包括 Feign 自带的注解,也支持使用第三方的注解,此外,Feign 还支持插件式的编码器和解码器,使用者可以通过该特性对请求和响应进行不同的封装与解析。

Feign 实际上会帮助我们动态生成代理类,使用的是 JDK 的动态代理,生成的代理类会将请求的信息封装,交给 feign.Client 接口发送请求,而接口的默认实现类会使用 java.net.HttpURLConnection 来发送 HTTP 请求。

Feign 使用示例

  • 创建项目

    创建Maven项目,命名为 feign-client,并增加 feign 依赖,POM.xml 内容如下:

    <?xmlversion="1.0"encoding="UTF-8"?>

    <projectxmlns="http://maven.apache.org/POM/4.0.0"

    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0http://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <groupId>org.lixue</groupId>

    <artifactId>feign-client</artifactId>

    <version>1.0-SNAPSHOT</version>

    <properties>

    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>

    <java.version>1.8</java.version>

    </properties>

    <dependencies>

    <dependency>

    <groupId>io.github.openfeign</groupId>

    <artifactId>feign-core</artifactId>

    <version>9.5.0</version>

    </dependency>

    <dependency>

    <groupId>io.github.openfeign</groupId>

    <artifactId>feign-gson</artifactId>

    <version>9.5.0</version>

    </dependency>

    </dependencies>

    </project>

  • 创建声明接口

    声明客户端共有3个方法,并使用 @RequestLine 注解说明了使用 GET 还是 POST 向服务器的指定 Url 提交数据,使用 @Param 注解标注了请求参数,如果是 POST 提交则不需要标注,@Headers 注解标注了请求头参数

    package org.lixue.feignclient;

    import feign.Headers;

    import feign.Param;

    import feign.RequestLine;

    public interface HelloWorldClient{

    @RequestLine("GET /speak?body={body}")

    String speak(@Param("body")String body);

    @RequestLine("GET /person/{personId}")

    Person findById(@Param("personId")Integer personId);

    @RequestLine("POST /person/create")

    @Headers("Content-Type:application/json")

    ReturnValue create(Person person);

    }

  • 测试验证

    speak 方法的提交参数和返回值均是基本类型,因此在调用的时候无需编码器和解码器;findById 方法的提交参数是基本类型,而返回值是对象,因此在调用的时候需要使用解码器将 JSON 字符串转换为对象;create 方法的提交参数和返回参数都是对象,因此在调用时需要使用编码器和解码器处理将对象转换为 JSON 字符串。

    package org.lixue.feignclient;

    import feign.Feign;

    import feign.gson.GsonDecoder;

    import feign.gson.GsonEncoder;

    public class Startup{

    public static void main(String[]args){

    HelloWorldClientspeakClient=

    Feign.builder().target(HelloWorldClient.class,"http://localhost:8080/");

    System.out.println(speakClient.speak("isbody"));

    HelloWorldClientfindByIdClient=

    Feign.builder().decoder(newGsonDecoder())

    .target(HelloWorldClient.class,"http://localhost:8080/");

    Person person=findByIdClient.findById(34);

    System.out.println("personid="+person.getId()+"age="+person.getAge()+"name="+person.getName()+"message="+person.getMessage());

    HelloWorldClientcreateClient=

    Feign.builder().decoder(newGsonDecoder())

    .encoder(newGsonEncoder())

    .target(HelloWorldClient.class,"http://localhost:8080/");

    Person newPerson=new Person();

    newPerson.setId(3434);

    newPerson.setAge(34);

    newPerson.setName("343434");

    newPerson.setMessage("33333333333333333");

    ReturnValue returnValue=createClient.create(newPerson);

    System.out.println(returnValue.parseString());

    }

    }

服务端代码

package org.lixue.webservices.services;

import org.springframework.beans.factory.annotation.Value;

import org.springframework.http.MediaType;

import org.springframework.web.bind.annotation.*;

@RestController

publicclassHelloWorldController{

@Value("${server.port}")

private int port;

@RequestMapping(method=RequestMethod.GET,name="speak",path="/speak")

public String speak(@RequestParam(value="body",required=false)String body){

if(body==null||body.equals("")){

return"helloworldport:"+port;

}

return"speak"+body+"port:"+port;

}

@RequestMapping(method=RequestMethod.GET,name="person",path="/person/{personId}",

produces=MediaType.APPLICATION_JSON_UTF8_VALUE)

public Person findById(@PathVariable("personId")Integer personId){

Person person=new Person();

person.setId(personId);

person.setAge(33);

person.setName("测试名称");

person.setMessage("id="+personId);

return person;

}

@RequestMapping(method=RequestMethod.POST,name="create",path="/person/create",

produces=MediaType.APPLICATION_JSON_UTF8_VALUE,consumes=MediaType.APPLICATION_JSON_UTF8_VALUE)

public ReturnValue createPerson(@RequestBody Person newPerson){

ReturnValue returnValue=new ReturnValue();

returnValue.setHasError(true);

returnValue.setMessage("测试消息");

return returnValue;

}

}

Feign 使用入门的更多相关文章

  1. Feign快速入门

    一.Feign简介1.Feign是一个声明式的web服务客户端,使用Feign编写web服务客户端更加容易2.具有可插拔注解支持,包括Feign注解和JAX-RS注解,还支持可插拔的编码器与解码器3. ...

  2. 声明式HTTP客户端-Feign 使用入门详解

    什么是 OpenFeign OpenFeign (以下统一简称为 Feign) 是 Netflix 开源的声明式 HTTP 客户端,集成了 Ribbon 的负载均衡.轮询算法和 RestTemplat ...

  3. Spring Cloud Feign 简单入门

    Feign是一个生命是的web service 客户端,使用方式非常简单:接口+注解,spring cloud feign 对feign惊醒了增强使它支持了spring mcv注解. 示例(以下示例结 ...

  4. Feign【入门】

    feign简介: feign是一种声明式,模板化的HTTP客户端,spring cloud对feign进行了增强,使其支持SpringMvc的相关注解,并整合了ribbon做负载均衡.在spring ...

  5. Spring Cloud(十一)声名式服务调用:Feign的使用 (上)

    一.写在前边 最近开发任务比较忙,下班也开始锻炼了,这个系列的文章就放了很久,看github我提交的Feign的入门程序已经好久了,今天正好得空,这就更上一贴,准备分几部分写 注意:之前几个项目中,笔 ...

  6. 【原创】SpringBoot & SpringCloud 快速入门学习笔记(完整示例)

    [原创]SpringBoot & SpringCloud 快速入门学习笔记(完整示例) 1月前在系统的学习SpringBoot和SpringCloud,同时整理了快速入门示例,方便能针对每个知 ...

  7. Spring Cloud Feign 优雅的服务调用

    Fegin 是由NetFlix开发的声明式.模板化HTTP客户端,可用于SpringCloud 的服务调用.提供了一套更优雅.便捷的HTTP调用API,并且SpringCloud整合了Fegin.Eu ...

  8. SpringCloud 源码系列(6)—— 声明式服务调用 Feign

    SpringCloud 源码系列(1)-- 注册中心 Eureka(上) SpringCloud 源码系列(2)-- 注册中心 Eureka(中) SpringCloud 源码系列(3)-- 注册中心 ...

  9. springcloud高级

    第一章 负载均衡 Ribbon   (Spring Cloud 高级)   一. Ribbon 在微服务中的作用   1 什么是 Ribbon   1.Ribbon 是一个基于 Http 和 TCP ...

随机推荐

  1. tp5 生成缩略图片

    我先说下我的思路,先把正常图片存到服务器,再通过代码将服务器上的大图压缩,生成新的小图替代大图 下面上代码 前台HTML代码 <div class="upload-btn"& ...

  2. python day09作业答案

    2. def lst(input): lst2=[] count=0 for i in range(0,len(input)): if i %2!=0: lst2.append(input[i]) r ...

  3. Python 类方法

    class Person: # 实例方法 def chi(self): print("人会吃") @classmethod # 装饰器, 此时这个方法是一个类方法 def he(c ...

  4. git之自学

  5. element.dataset API

    不久之前我向大家展示了非常有用的classList API,它是一种HTML5里提供的原生的对页面元素的CSS类进行增.删改的接口,完全可以替代jQuery里的那些CSS类操作方法.而另外一个非常有用 ...

  6. 运行和管理Rabbit

    节点描述的是一个Erlang节点运行着一个Erlang应用程序.Erlang虚拟机的每个实例我们称之为节点.多个Erlang应用程序可以运行在同一个节点之上.节点之间可以进行本地通信.在RabbitM ...

  7. JavaScript操作符-3---算数,逻辑,赋值,比较,三元

    JavaScript操作符 学习目标 1.掌握什么是表达式 2.掌握javascript操作符的分类 3.掌握算数操作符 什么是表达式 将类型的数据(如常量.变量.函数等),用运算符号按一定的规则链接 ...

  8. python调用caffe实现预测

    对于已经训练完成的caffemodel,对于单个的图片预测,用python接口来调用是一件非常方便的事情,下面就来讲述如何用python调用已经训练完成的caffemodel,以及prototxt,网 ...

  9. Linux more命令详解

    more功能类似 cat ,cat命令是整个文件的内容从上到下显示在屏幕上. more会以一页一页的显示方便使用者逐页阅读,而最基本的指令就是按空白键(space)就往下一页显示,按 b 键就会往回( ...

  10. python三大框架之一flask中cookie和session的相关操作

    状态保持 Cookie cookie 是指某些网站为了 辨别  用户身份,进行会话跟踪而储存在用户本地的数据(通常会经过加密),复数形式是 coolies. cookie是由服务器端生成,发送给客户端 ...