Feign是spring cloud中服務(wù)消費端的調(diào)用框架,通常與ribbon,hystrix等組合使用。
但是在某些項目中,由于遺留原因,整個系統(tǒng)并不是spring cloud項目,甚至不是spring項目,而使用者關(guān)注的重點僅僅是簡化http調(diào)用代碼的編寫。
如果采用httpclient或者okhttp這樣相對較重的框架,對初學(xué)者來說編碼量與學(xué)習(xí)曲線都會是一個挑戰(zhàn),而使用spring中RestTemplate,又沒有配置化的解決方案,由此想到是否可以脫離spring cloud,獨立使用Feign。
maven依賴
<dependency>
<groupId>com.netflix.feign</groupId>
<artifactId>feign-core</artifactId>
<version>8.18.0</version>
</dependency>
自定義接口
import feign.Param;
import feign.RequestLine;
public interface RemoteService {
@RequestLine("GET /users/list?name={name}")
String getOwner(@Param(value = "name") String name);
}
通過@RequestLine指定HTTP協(xié)議及URL地址
配置類
RemoteService service = Feign.builder()
.options(new Options(1000, 3500))
.retryer(new Retryer.Default(5000, 5000, 3))
.target(RemoteService.class, "http://127.0.0.1:8085");
options方法指定連接超時時長及響應(yīng)超時時長,retryer方法指定重試策略,target方法綁定接口與服務(wù)端地址。返回類型為綁定的接口類型。
調(diào)用
String result = service.getOwner("scott");
與調(diào)用本地方法相同的方式調(diào)用feign包裝的接口,直接獲取遠程服務(wù)提供的返回值。
附:服務(wù)生產(chǎn)者
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping(value="users")
public class UserController {
@RequestMapping(value="/list",method={RequestMethod.GET,RequestMethod.POST,RequestMethod.PUT})
@ResponseBody
public String list(@RequestParam String name) throws InterruptedException{
return name.toUpperCase();
}
}
更進一步
在項目中,服務(wù)消費端與生產(chǎn)端之間交換的數(shù)據(jù)往往是一或多個對象,feign同樣提供基于json的對象轉(zhuǎn)換工具,方便我們直接以對象形式交互。
業(yè)務(wù)接口
public interface RemoteService {
@Headers({"Content-Type: application/json","Accept: application/json"})
@RequestLine("POST /users/list")
User getOwner(User user);
}
加入@Headers注解,指定Content-Type為json
配置
RemoteService service = Feign.builder()
.encoder(new JacksonEncoder())
.decoder(new JacksonDecoder())
.options(new Options(1000, 3500))
.retryer(new Retryer.Default(5000, 5000, 3))
.target(RemoteService.class, "http://127.0.0.1:8085");
encoder指定對象編碼方式,decoder指定對象解碼方式。這里用的是基于Jackson的編、解碼方式,需要在pom.xml中添加Jackson的依賴
<dependency>
<groupId>com.netflix.feign</groupId>
<artifactId>feign-jackson</artifactId>
<version>8.18.0</version>
</dependency>
調(diào)用
User result = service.getOwner(u);
附:服務(wù)生產(chǎn)者
@Controller
@RequestMapping(value="users")
public class UserController {
@RequestMapping(value="/list",method={RequestMethod.GET,RequestMethod.POST,RequestMethod.PUT})
@ResponseBody
public User list(@RequestBody User user) throws InterruptedException{
System.out.println(user.getUsername());
user.setId(100L);
user.setUsername(user.getUsername().toUpperCase());
return user;
}
}
唯一的變化就是使用了@RequestBody來接收json格式的數(shù)據(jù)。