一、Feign的使用(客户端调用 json/xml格式的接口)

1.服务端接口编写

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.2.RELEASE</version>
</parent> <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency> <dependency>
<groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-jaxrs-xml-provider</artifactId>
<version>2.9.0</version>
</dependency>
</dependencies>
  @RequestMapping(value = "/hello", method = RequestMethod.GET)
public String hello() {
return "hello world";
} @RequestMapping(value = "/person/create", method = RequestMethod.POST,
produces = MediaType.APPLICATION_JSON_VALUE,
consumes = MediaType.APPLICATION_JSON_VALUE)
public String createPerson(@RequestBody Person person) {
System.out.println(person.getName() + "~~~~~~~" +person.getAge());
return "success, id:" + person.getId();
} @RequestMapping(value = "/createXmlPerson/create", method = RequestMethod.POST,
produces = MediaType.APPLICATION_XML_VALUE,
consumes = MediaType.APPLICATION_XML_VALUE)
public String createXmlPerson(@RequestBody Person person) {
System.out.println(person.getName() + "~~~~~~~" +person.getAge());
return "<result><message>success</message></result>";
}

2.客户端编写

(1)导入jar包

<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> <!--配置xml客户端-->
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-jaxb</artifactId>
<version>9.5.0</version>
</dependency> <dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.20</version>
</dependency> <dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.0</version>
</dependency> <!--httpclient-->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.5</version>
</dependency>
</dependencies>

(2)编写客户端测试代码

public interface ClientInterface {

    @RequestLine("GET /hello")
public String hello(); @RequestLine("GET /person/{id}")
public Person getPerson(@Param("id") Integer id); @RequestLine("POST /person/create")
@Headers("Content-Type: application/json")
public String createPerson(Person person); @RequestLine("POST /createXmlPerson/create")
@Headers("Content-Type: application/xml")
public Result createXmlPerson(Person person);
}
public static void main(String[] args) {
//hello
ClientInterface helloClient = Feign.builder().target(ClientInterface.class, "http://localhost:8080"); String hello = helloClient.hello();
System.out.println(hello); //json 创建 Person
ClientInterface creatPersonInter = Feign.builder()
.encoder(new GsonEncoder())
.target(ClientInterface.class, "http://localhost:8080"); Person person = new Person();
person.setAge(18);
person.setId(1);
person.setName("admin"); String result = creatPersonInter.createPerson(person);
System.out.println("result:" + result); //xml 创建 Person
JAXBContextFactory jaxbContextFactory = new JAXBContextFactory.Builder().build();
ClientInterface xmlClient = Feign.builder().encoder(new JAXBEncoder(jaxbContextFactory))
.decoder(new JAXBDecoder(jaxbContextFactory))
.target(ClientInterface.class, "http://localhost:8080/"); Person person1 = new Person();
person1.setAge(18);
person1.setId(1);
person1.setName("admin");
Result result2 = xmlClient.createXmlPerson(person1);
System.out.println("result:"+result2.getMessage());
}

二、自定义Feign客户端

1.编写myClient

import feign.Client;
import feign.Request;
import feign.Response;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils; import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Collection;
import java.util.HashMap; public class MyClient implements Client {
@Override
public Response execute(Request request, Request.Options options) throws IOException {
try {
System.out.println("自定义的client"); //创建一个默认的客户端
CloseableHttpClient httpClient = HttpClients.createDefault(); //获取调用的http方法
final String method = request.method(); //创建一个HttpClient 的 HttpRequest
HttpRequestBase httpRequestBase = new HttpRequestBase() {
@Override
public String getMethod() {
return method;
}
}; //设置请求地址
httpRequestBase.setURI(new URI(request.url())); //执行请求,获取响应
HttpResponse httpResponse = httpClient.execute(httpRequestBase); //获取响应的内容
byte[] body = EntityUtils.toByteArray(httpResponse.getEntity()); //将HttpClient d的响应对象转换为Feign的Response
Response response = Response.builder()
.body(body)
.headers(new HashMap<String, Collection<String>>())
.status(httpResponse.getStatusLine().getStatusCode())
.build();
return response;
} catch (URISyntaxException e) {
e.printStackTrace();
}
return null;
}
}

2.编写MyClientTest测试

public static void main(String[] args) {
ClientInterface clientInterface = Feign.builder()
.client(new MyClient())
.target(ClientInterface.class, "http://localhost:8080"); String hello = clientInterface.hello();
System.out.println(hello);
}

Feign 客户端的使用 二的更多相关文章

  1. Spring Cloud之Feign客户端超时时间配置

    关于雪崩效应: 默认情况下tomcat只有一个线程去处理客户端发送的所有请求.高并发情况下,如果客户端请求都在同一接口,tomcat的所有线程池去处理,导致其他接口服务访问不了,等待. Tomcat有 ...

  2. Spring Cloud之Feign客户端调用工具

    feign介绍 Feign客户端是一个web声明式http远程调用工具,提供了接口和注解方式进行调用. Spring Cloud 支持 RestTemplate  Fetin Feign客户端实际开发 ...

  3. Spring Boot使用Feign客户端调用远程服务时出现:timed-out and no fallback available,failed and no fallback available的问题解决

    timed-out and no fallback available: 这个错误基本是出现在Hystrix熔断器,熔断器的作用是判断该服务能不能通,如果通了就不管了,调用在指定时间内超时时,就会通过 ...

  4. Feign 客户端调用错误

    1.@RequestBody 必须要写在实现接口中 2.Feign 客户端调用的时候如果有参数的话,默认是发送post请求 3.服务接口中的请求参数必须要加上@RequestParam("r ...

  5. Springcloud 整合Hystrix 断路器,支持Feign客户端调用

    1,在这篇博文中,已经大致说过了Springcloud服务保护框架 Hystrix在服务隔离,服务降级,以及服务熔断中的使用 https://www.cnblogs.com/pickKnow/p/11 ...

  6. Feign客户端的重构,新建springcloud架构

    1,在上篇博文中,已经实现了feign 客户端来远程调用接口的功能,因为feign 客户端在springcloud 开发过程中是比较常用的方式 https://www.cnblogs.com/pick ...

  7. Feign客户端实现RPC 调用

    1,springcloud 中支持http调用的两种方式,RestTemplate,Feign客户端 2,Feign 客户端是一个声明式(注解方式)http 远程调用工具 3,实现方式如下: 第一步: ...

  8. WCF学习之旅—实现支持REST客户端应用(二十四)

    WCF学习之旅—实现REST服务(二十二) WCF学习之旅—实现支持REST服务端应用(二十三) 在上二篇文章中简单介绍了一下RestFul与WCF支持RestFul所提供的方法,及创建一个支持RES ...

  9. Jquery.Qrcode在客户端动态生成二维码并添加自定义Logo

    0 Jquery.Qrcode简介 Jquery.Qrcode.js是一个在浏览器端基于Jquery动态生成二维码的插件,支持Canvas和Table两种渲染方式,它的优点是在客户端动态生成,减轻了服 ...

随机推荐

  1. 郑宇以城市计算研究膺选 MIT 科技创新35俊杰 (TR35)

    MIT 科技创新35俊杰 (TR35)"> 编者按:<MIT Technology Review>于8月22日发布了令人瞩目的2013年全球杰出青年创新者(MIT TR35 ...

  2. Go-Micro框架入门教程(一)---框架结构

    Go语言微服务系列文章,使用golang实现微服务,这里选用的是go-micro框架,本文主要是对该框架的一个架构简单介绍. 1. 概述 go-micro是go语言下的一个很好的微服务框架. 1.服务 ...

  3. json转换为go类文件,js脚本,nodejs执行

    js写的代码生成脚本,json生成对应的go type对象 作json转换用 js脚本无甚何依赖,可以直接运行 执行前,按需更改文件 示例 var topname="Data"; ...

  4. rocket mq 入门文档

    原文地址: http://jm.taobao.org/2017/01/12/rocketmq-quick-start-in-10-minutes/ 感谢原作者 十分钟入门RocketMQ 本文首先引出 ...

  5. RabbitMQ(1)——基础入门

    本文章写在了CSDN :https://blog.csdn.net/qq_30348181/article/details/87911398

  6. in与exist , not in与not exist 的区别

    in和exists     in 是把外表和内表作hash 连接,而exists是对外表作loop循环,每次loop循环再对内表进行查询.一直以来认为exists比in效率高的说法是不准确的.     ...

  7. [hdu4630] No Pain No Game

    某次模拟赛的T1. 刚开始怀疑是RMQ......我真是太弱了QAQ 题目传送门 正解是离线操作,把所有询问按r从小到大排序. 然后把数从左到右处理,处理完第i个数,就可以回答所有r==i的询问了. ...

  8. Problem 43 // Project Euler

    Sub-string divisibility The number, 1406357289, is a 0 to 9 pandigital number because it is made up ...

  9. python语法生成器、迭代器、闭包、装饰器总结

    1.生成器 生成器的创建方法: (1)通过列表生成式创建 可以通过将列表生成式的[]改成() eg: # 列表生成式 L = [ x*2 for x in range(5)] # L = [0, 2, ...

  10. 传智播客学习之Android运行原理 (转)

    传智播客学习之Android运行原理 (2010-03-20 22:45:15) 转载▼ 今天终于忙里偷闲,和大家探讨一下android技术,第一次听到3G应该追溯到大学三年级的时候了,记得当时现代通 ...