今天在項目上遇到一個問題,通過當前service服務要調用到其他service服務的api接口時,可通過EnableFeignClients調用其他服務的api,大概的步驟如下:
1、在springboot的main處加上注解@EnableFeignClients
1 @EnableDiscoveryClient 2 @SpringBootApplication 3 @EnableFeignClients 4 public class MyServiceApplication { 5 6 public static void main(String[] args){ 7 SpringApplication.run(MyServiceApplication.class, args); 8 } 9 10 }
2、在service層上實現接口,這里注意value可以用serviceId代替,但是最好用value來指定要調用的服務。
fallback是當程序錯誤的時候來回調的方法
方法中要用@PathVariable要注解參數
1 @FeignClient(value = "other-service", fallback = ExampleFeignClientFallback.class) 2 public interface ExampleFeignClient { 3 @RequestMapping(value = "/v1/exampleId/{id}",method = RequestMethod.GET) 4 Long queryById(@PathVariable(name="id") Long id); 5 }
3、編寫程序錯誤時的回調類,實現接口,在錯誤時回調
1 @Service 2 public class ExampleFeignClientFallback implements ExampleFeignClient { 3 @Override 4 public Long queryById(Long id) { 5 return null; 6 } 7 }
4、調用該服務
1 //聲明,自動封裝 2 @Autowired 3 private ExampleFeignClient ExampleFeignClient; 4 5 6 //調用 7 Long result = ExampleFeignClient.queryById(id);
至此,完成整個步驟