zoukankan      html  css  js  c++  java
  • 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;

    }

    }

       

  • 相关阅读:
    fastJson Gson对比及java序列化问题
    HashMap遍历时的性能对比
    FileChannel与ByteBuffer的使用示例
    spring boot中ConditionalOnClass为什么没有classNotFound类加载异常
    maven插件: shade, assembly
    spring容器中的beanName
    线程状态
    IDEA插件
    IDEA 工具使用指南
    方法调用:对象的传值与传引用
  • 原文地址:https://www.cnblogs.com/li3807/p/8890619.html
Copyright © 2011-2022 走看看