SpringCloud服務間的調用有兩種方式:RestTemplate和FeignClient。不管是什么方式,他都是通過REST接口調用服務的http接口,參數和結果默認都是通過jackson序列化和反序列化。因為Spring MVC的RestController定義的接口,返回的數據都是通過Jackson序列化成JSON數據。
一、RestTemplate
使用這種方式,只需要定義一個RestTemplate的Bean,設置成LoadBalanced即可。
如下示例:
@Configuration public class SomeCloudConfiguration { @LoadBalanced @Bean RestTemplate restTemplate() { return new RestTemplate(); } }
這樣我們就可以在需要用的地方注入這個bean使用:
public class SomeServiceClass { @Autowired private RestTemplate restTemplate; public String getUserById(Long userId) { UserDTO results = restTemplate.getForObject("http://users/getUserDetail/" + userId, UserDTO.class); return results; } }
其它示例參考:
@SpringBootApplication public class SleuthClientApplication { @Bean public RestTemplate restTemplate() { return new RestTemplate(); } public static void main(String[] args) { SpringApplication.run(SleuthClientApplication.class, args); } } @RestController class HomeController { private static final Log log = LogFactory.getLog(HomeController.class); @Autowired private RestTemplate restTemplate; private String url="http://localhost:9986"; @RequestMapping("/service1") public String service1() throws Exception { log.info("service1"); Thread.sleep(200L); String s = this.restTemplate.getForObject(url + "/service2", String.class); return s; } }
二、FeignClient
除了上面的方式,我們還可以用FeignClient。
@FeignClient(value = "users", path = "/users") public interface UserCompositeService { @RequestMapping(value = "/getUserDetail/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) UserDTO getUserById(@PathVariable Long id); }
我們只需要使用@FeignClient定義一個接口,Spring Cloud Feign會幫我們生成一個它的實現,從相應的users服務獲取數據。
其中,@FeignClient(value = “users”, path = “/users/getUserDetail”)里面的value是服務ID,path是這一組接口的path前綴。在下面的方法定義里,就好像設置Spring MVC的接口一樣,對於這個方法,它對應的URL是/users/getUserDetail/{id}。然后,在使用它的時候,就像注入一個一般的服務一樣注入后使用即可:
public class SomeOtherServiceClass { @Autowired private UserCompositeService userService; public void doSomething() { // ..... UserDTO results = userService.getUserById(userId); // other operation... } }
其中遇到的坑請參見:http://dockone.io/article/2140