博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Feign 客户端的使用 二
阅读量:6254 次
发布时间:2019-06-22

本文共 6163 字,大约阅读时间需要 20 分钟。

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

1.服务端接口编写

org.springframework.boot
spring-boot-starter-parent
2.0.2.RELEASE
org.springframework.boot
spring-boot-starter-web
com.fasterxml.jackson.jaxrs
jackson-jaxrs-xml-provider
2.9.0
  @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 "
success
"; }

2.客户端编写

(1)导入jar包

io.github.openfeign
feign-core
9.5.0
io.github.openfeign
feign-gson
9.5.0
io.github.openfeign
feign-jaxb
9.5.0
org.projectlombok
lombok
1.16.20
javax.xml.bind
jaxb-api
2.3.0
org.apache.httpcomponents
httpclient
4.5.5

(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
>()) .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);    }

 

转载于:https://www.cnblogs.com/gyli20170901/p/10082051.html

你可能感兴趣的文章
Fragment总结
查看>>
Flutter进阶:深入探究 ListView 和 ScrollPhysics
查看>>
深入了解virtual dom
查看>>
spring事物应该注意的地方
查看>>
浅析 Vue 2.6 中的 nextTick 方法
查看>>
一篇文章搞懂闭包。
查看>>
结合实际场景谈一谈微服务配置
查看>>
我的前端面试总结(套路篇)
查看>>
ApacheCN 学习资源汇总 2018.11
查看>>
数字滚动插件numberAnimate.js的使用及效果修改
查看>>
从JS引擎理解Await b()与Promise.then(b)的堆栈处理
查看>>
深度学习-初识
查看>>
十分钟理解Redux核心思想,过目不忘。
查看>>
非对称加密技术- RSA算法数学原理分析
查看>>
PHP学习记录(基础)
查看>>
tweak 中常用的方法调用方法和 运行时API
查看>>
redis的incr和hash应用
查看>>
Laravel5.2 自定义Facades
查看>>
前端开发知识点之javascript
查看>>
慕课网_《模式的秘密之工厂模式》学习总结
查看>>