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;

}

}

   


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM