feign是什麼
用官方文檔的話來解釋:
feign是一個聲明性web服務客戶端。它使編寫web服務客戶端變得更容易。使用feign創建一個接口並對其進行註釋。它有可插入的註釋支持,包括外部註釋和jax-rs註釋。feign還支持可插入的編碼器和解碼器。spring cloud增加了對spring mvc註釋的支持,以及對使用spring web中默認使用的httpMessageConverter的支持。spring cloud集成了ribbon和eureka,在使用feign時提供了一個負載平衡的http客戶端。
如何使用
首先要引入以下依賴,feign是集成了ribbon的
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
在啓動類開啓對feign的支持@EnableFeignClients
@SpringBootApplication
@EnableEurekaClient
@RibbonClients({
@RibbonClient(name="server-user",configuration = UserConfig.class),
@RibbonClient(name="server-order",configuration = OrderConfig.class)
})
@EnableFeignClients
public class PowerApplication {
public static void main(String[] args) {
SpringApplication.run(PowerApplication.class, args);
}
}
feign服務
@FeignClient("server-user")
public interface FeignService {
@RequestMapping("/hello")
Map getUser();
}
@RestController
public class FeignController {
@Autowired
FeignService feignService;
@RequestMapping("/getFeignUser")
public Map getFeignUser(){
return feignService.getUser();
}
}
如果不想用自己的配置
官網上推薦的方式是
@FeignClient(name = "stores", configuration = FooConfiguration.class)
public interface StoreClient {
//..
}
fooconfiguration不需要用@configuration註釋。但是,如果是,請注意將其從任何@componentscan中排除,否則將包含此配置,因爲當指定時,它將成爲feign.decoder、feign.encoder、feign.contract等的默認源。這可以通過將它與任何@componentscan或@springbootsapplication放在一個單獨的、不重疊的包中來避免,也可以在@componentscan中顯式排除它。
也可以通過配置文件的方式
application.yml
feign:
client:
config:
feignName:
connectTimeout: 5000
readTimeout: 5000
loggerLevel: full
errorDecoder: com.example.SimpleErrorDecoder
retryer: com.example.SimpleRetryer
requestInterceptors:
- com.example.FooRequestInterceptor
- com.example.BarRequestInterceptor
decode404: false
encoder: com.example.SimpleEncoder
decoder: com.example.SimpleDecoder
contract: com.example.SimpleContract
默認配置可以在@enablefeignclients屬性defaultconfiguration中以類似的方式指定,如上所述。不同之處在於,此配置將應用於所有外部客戶端。
如果您喜歡使用配置屬性來配置所有@feignclient,那麼可以使用默認的feign名稱創建配置屬性。
application.yml
feign:
client:
config:
default:
connectTimeout: 5000
readTimeout: 5000
loggerLevel: basic
官網上說java bean的方式和配置文件都存在時,配置文件的優先級較高,但是沒測試過,也沒人會兩者都配置吧。