Feign 使用入门
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 使用入门的更多相关文章
- Feign快速入门
一.Feign简介1.Feign是一个声明式的web服务客户端,使用Feign编写web服务客户端更加容易2.具有可插拔注解支持,包括Feign注解和JAX-RS注解,还支持可插拔的编码器与解码器3. ...
- 声明式HTTP客户端-Feign 使用入门详解
什么是 OpenFeign OpenFeign (以下统一简称为 Feign) 是 Netflix 开源的声明式 HTTP 客户端,集成了 Ribbon 的负载均衡.轮询算法和 RestTemplat ...
- Spring Cloud Feign 简单入门
Feign是一个生命是的web service 客户端,使用方式非常简单:接口+注解,spring cloud feign 对feign惊醒了增强使它支持了spring mcv注解. 示例(以下示例结 ...
- Feign【入门】
feign简介: feign是一种声明式,模板化的HTTP客户端,spring cloud对feign进行了增强,使其支持SpringMvc的相关注解,并整合了ribbon做负载均衡.在spring ...
- Spring Cloud(十一)声名式服务调用:Feign的使用 (上)
一.写在前边 最近开发任务比较忙,下班也开始锻炼了,这个系列的文章就放了很久,看github我提交的Feign的入门程序已经好久了,今天正好得空,这就更上一贴,准备分几部分写 注意:之前几个项目中,笔 ...
- 【原创】SpringBoot & SpringCloud 快速入门学习笔记(完整示例)
[原创]SpringBoot & SpringCloud 快速入门学习笔记(完整示例) 1月前在系统的学习SpringBoot和SpringCloud,同时整理了快速入门示例,方便能针对每个知 ...
- Spring Cloud Feign 优雅的服务调用
Fegin 是由NetFlix开发的声明式.模板化HTTP客户端,可用于SpringCloud 的服务调用.提供了一套更优雅.便捷的HTTP调用API,并且SpringCloud整合了Fegin.Eu ...
- SpringCloud 源码系列(6)—— 声明式服务调用 Feign
SpringCloud 源码系列(1)-- 注册中心 Eureka(上) SpringCloud 源码系列(2)-- 注册中心 Eureka(中) SpringCloud 源码系列(3)-- 注册中心 ...
- springcloud高级
第一章 负载均衡 Ribbon (Spring Cloud 高级) 一. Ribbon 在微服务中的作用 1 什么是 Ribbon 1.Ribbon 是一个基于 Http 和 TCP ...
随机推荐
- VSFTP服务配置
FTP连接及传输模式控制连接:TCP 21 ,用于发送FTP命令信息数据连接:TCP 20 ,用于上传.下载数据数据连接的建立类型:主动模式.被动模式 主动模式:服务器主动发起数据连接·首先由客户端向 ...
- c#帮助文档chm打不开的问题
c# 帮助文档,chm 格式, 不可以放在含有字符 # 的文件夹下(包括当前文件夹和上级文件夹),文件名也不可以含有 # 字符, 否则会打不开.
- Java中的容器 I————浅谈Queue和PriorityQueue
一.Queue的实现 通过LinkedList类实现Queue接口来完成对Queue的实例类的实现,代码如下: Queue<Integer> queue=new LinkedList< ...
- xdoj-1022-A simple math problem 2 // 太强了
//其实题目中f[n]的值可理解为存在多少个整数对使a*b<=n #include<cstdio> #define N 1007 #define maxn 1000005 using ...
- Flutter,H5,React Native
Flutter介绍 - Flutter,H5,React Native之间的对比 Flutter介绍 Flutter是Google推出的开源移动应用开发框架.开发者可以通过开发一套代码同时运行在i ...
- Blender Tutorial - Earth curves [Animation nodes]笔记
https://www.youtube.com/watch?v=jEYI4lnOprY&t= Blender Tutorial - Earth curves [Animation nodes] ...
- (20)jQuery的文档操作(创建,添加、设置样式和删除等)
<!DOCTYPE html><html><head> <meta charset="UTF-8"> <title>jq ...
- struts2文件上传1
<form action="hello/UploadAction_upload.action" enctype="multipart/form-data" ...
- HashMap的四种遍历方法,及效率比较(简单明了)
https://yq.aliyun.com/ziliao/210955 public static void main(String[] args) { HashMap<Integer, Str ...
- 工作记录[续] android OBB
前两篇在这里: Android上使用native IO 最近工作中的问题笔记 最近遇到的问题是, java.io.IOException: FAT Full StackOverflow的结果: htt ...