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. python中pass语句的作用是什么

    pass语句不会执行任何操作,一般作为占位符或者创建站位程序,whileFalse:pass.

  2. java学习笔记5(方法)

    方法: 1.如何创建方法 修饰符   返回值类型  方法名(参数){被封装的代码段} 2.方法的定义和使用的注意事项: a:方法不能定义在另一个方法里面: b:方法 名字和方法的参数列表,定义和调用时 ...

  3. [转载] About Career Promotion and Tutoring from Zhihu Web FAQer (Quoted Entirely Without Personal Idea. Delete Immediately If Pirated)

    问题: 如何下列各类公司的互联网IT类工作待遇排名? 下列各公司岗位待遇序号从小到大依次降低: 美国互联网总部special offer(15万刀起薪) : 股份制银行总行,证券公司,基金公司IT部门 ...

  4. github上DQN代码的环境搭建,及运行(Human-Level Control through Deep Reinforcement Learning)conda配置

    最近师弟在做DQN的实验,由于是强化学习方面的东西,正好和我现在的研究方向一样于是我便帮忙跑了跑实验,于是就有了今天的这个内容. 首先在github上进行搜寻,如下图: 发现第一个星数最多,而且远高于 ...

  5. tf.contrib.rnn.core_rnn_cell.BasicLSTMCell should be replaced by tf.contrib.rnn.BasicLSTMCell.

    For Tensorflow 1.2 and Keras 2.0, the line tf.contrib.rnn.core_rnn_cell.BasicLSTMCell should be repl ...

  6. Unity 3D用简单的Cube、Sphere实现镜面/哈哈镜效果,只需十几秒哦!

    Unity实现镜面和哈哈镜效果 本文提供全流程,中文翻译. Chinar 坚持将简单的生活方式,带给世人!(拥有更好的阅读体验 -- 高分辨率用户请根据需求调整网页缩放比例) Chinar -- 心分 ...

  7. POJ - 1474 :Video Surveillance (半平面交-求核)

    pro:顺时针给定多边形,问是否可以放一个监控,可以监控到所有地方,即问是否存在多边形的核. 此题如果两点在同一边界上(且没有被隔段),也可以相互看到. sol:求多边形是否有核.先给直线按角度排序, ...

  8. PTA——模拟除法

    PTA 7-42 整除光棍 #include <stdio.h> int main() { ];//创建存表 ,count=; int n; ; scanf("%d", ...

  9. oracle 日常

    oracle  sql server  select  1 from dual  和   select 1    nvl(null,0)     为空显示 0 greatest (1, 3, 2 )  ...

  10. wireshark显示过滤器的几种用法(转自他人博客)

    本文章转自:http://blog.51cto.com/houm01/1872652 几种条件操作符 ==   eq    等于    ip.addr == 192.168.0.1   ip.addr ...