Feign是一個聲明式的僞RPC(Feign英文意思為“假裝,僞裝,變形”)的REST用戶端,它用了基于接口的注解方式,可以以Java接口注解的方式調用Http請求,進而将請求子產品化。Feign被廣泛應用在Spring Cloud的解決方案中,是學習基于Spring Cloud微服務架構不可或缺的重要元件。
使用
1、添加依賴
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
2、啟動類添加@EnableFeignClients注解
3、定義注解接口
@FeignClient注解裡面的user-server為調用服務名
package demo.newsweb.controller;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
@FeignClient("user-server")
public interface UserControllerFeign {
@GetMapping("/user/login")
String login(@RequestParam("user") String user, @RequestParam("pwd") String pwd);
}
4、使用注解接口遠端調用
package demo.newsweb.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("user")
public class UserController {
@Autowired
private UserControllerFeign userControllerFeign;
@GetMapping("/login")
public String login(String user, String pwd) {
return userControllerFeign.login(user, pwd);
}
}
特性
開啟Gzip壓縮
# 請求開啟壓縮
feign.compression.request.enabled=true
# 最小壓縮大小(字元),低于這個值則不壓縮
feign.compression.request.min-request-size=2048
# 響應開啟壓縮
feign.compression.response.enabled=true
# 壓縮類型 "text/xml", "application/xml", "application/json"
feign.compression.request.mime-types=text/xml,application/xml,application/json
Feign日志配置
1、配置日志輸出級别
# 日志級别
logging.level.[demo.newsweb.controller.UserControllerFeign]=debug
2、配置日志輸出方式
FULL為輸出全部資訊。
package demo.newsweb.controller;
import feign.Logger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class FeginLogConfig {
@Bean
Logger.Level feignLogger() {
return Logger.Level.FULL;
}
}
3、Feign接口注解@FeignClient加入configuration = FeginLogConfig.class使用設定的日志輸出方式
package demo.newsweb.controller;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
@FeignClient(value = "user-server",configuration = FeginLogConfig.class)
public interface UserControllerFeign {
@GetMapping("/user/login")
String login(@RequestParam("user") String user, @RequestParam("pwd") String pwd);
}
輸出資訊如下
替換預設的底層通信
底層通信預設是URLConnection,可替換成性能更好的okHttp
添加依賴
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-okhttp</artifactId>
</dependency>
添加配置啟用
feign.httpclient.enabled=false
feign.okhttp.enabled=true