項目終于用上了動態(tài)Feign,真香!
Feign在微服務框架中使得服務直接的調用變得很簡潔、簡單,而不需要再編寫Java Http調用其他微服務的接口。
動態(tài)feign
對于fegin調用,我們一般的用法:為每個微服務都創(chuàng)建對應的feignclient接口,然后為每個微服務的controller接口,一一編寫對應的方法,去調用對應微服務的接口。
例如下面這樣:
//system
@FeignClient(name = "system")
publicinterface SystemClient {
@GetMapping("/system/test1")
JsonResult test1(String test1);
@GetMapping("/system/test2")
JsonResult test2(String test2);
....
}
//user
@FeignClient(name = "user")
publicinterface UserClient {
@GetMapping("/user/test1")
JsonResult test1(String test1);
@GetMapping("/user/test2")
JsonResult test2(String test2);
....
}
這樣寫的話,可能會有些累贅,那么我們能不能創(chuàng)建一個動態(tài)的feign;當調用sytem微服務的時候,傳遞一個feignclient的name為system進去,然后定義一個通用的方法,指定調用的url,傳遞的參數(shù),就可以了呢?
答案是可以的!!!^_^
定義一個通用的接口,通用的get,post方法:
public interface DynamicService {
@PostMapping("{url}")
Object executePostApi(@PathVariable("url") String url, @RequestBody Object params);
@GetMapping("{url}")
Object executeGetApi(@PathVariable("url") String url, @SpringQueryMap Object params);
}
executePostApi:(post方法)
- url,表示你要調用微服務的接口url,一般來說是對應controller接口的url;
- params,為調用該接口所傳遞的參數(shù),這里加了@RequestBody,那對應的controller接口,接收參數(shù)也需要加上該注解。
定義一個動態(tài)feignclient:
@Component
publicclass DynamicClient {
@Autowired
private DynamicFeignClientFactory<DynamicService> dynamicFeignClientFactory;
public Object executePostApi(String feignName, String url, Object params) {
DynamicService dynamicService = dynamicFeignClientFactory.getFeignClient(DynamicService.class, feignName);
return dynamicService.executePostApi(url, params);
}
public Object executeGetApi(String feignName, String url, Object params) {
DynamicService dynamicService = dynamicFeignClientFactory.getFeignClient(DynamicService.class, feignName);
return dynamicService.executeGetApi(url, params);
}
}
executePostApi:(post方法)
- feignName,表示需要調用的微服務的名稱,一般對應application.name,例如:system
- url,表示你要調用微服務的接口url,一般來說是對應controller接口的url;
- params,為調用該接口所傳遞的參數(shù),這里加了@RequestBody,那對應的controller接口,接收參數(shù)也需要加上該注解。
定義一個動態(tài)feignclient工廠類:
@Component
public class DynamicFeignClientFactory<T> {
private FeignClientBuilder feignClientBuilder;
public DynamicFeignClientFactory(ApplicationContext appContext) {
this.feignClientBuilder = new FeignClientBuilder(appContext);
}
public T getFeignClient(final Class<T> type, String serviceId) {
return this.feignClientBuilder.forType(type, serviceId).build();
}
}
主要的作用:是幫我們動態(tài)的創(chuàng)建一個feignclient對象
好了,具體的操作步驟,就是上面所說的了!!!是不是很通用了呢?
通用是通用了,那怎么玩呢(如何使用)?
使用的方式,也是十分的簡單啦:^_^
DynamicClient dynamicClient = SpringUtil.getBean(DynamicClient.class);
Object result = dynamicClient.executePostApi("system", "/system/test", new HashMap<>());
System.out.println("==========>"+JSONObject.toJSONString(result));
先獲取到DynamicClient對象,然后直接調用executePostApi方法:
- "system",表示調用微服務的名稱,一般對應application.name
- "/system/test",表示調用的url
- new HashMap<>(),為需要傳遞的參數(shù)
好了,這樣就實現(xiàn)了一個通用版的feignclient,那我們就可以愉快的編寫代碼了!!!^_^