There are two ways to call between SpringCloud services: RestTemplate and FeignClient . No matter what the method is, he calls the http interface of the service through the REST interface, and the parameters and results are serialized and deserialized through jackson by default . Because of the interface defined by Spring MVC 's RestController , the returned data is serialized into JSON data through Jackson .
1. RestTemplate
In this way, you only need to define a RestTemplate Bean and set it to LoadBalanced .
The following example:
1 2 3 4 5 6 7 8 |
@Configuration public class SomeCloudConfiguration { @LoadBalanced @Bean RestTemplate restTemplate() { return new RestTemplate(); } } |
This way we can inject this bean to use where we need it:
1 2 3 4 5 6 7 8 |
public class SomeServiceClass { @Autowired private RestTemplate restTemplate; public String getUserById(Long userId) { UserDTO results = restTemplate.getForObject("http://users/getUserDetail/" + userId, UserDTO.class); return results; } } |
Other example references:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
@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。
1 2 3 4 5 6 7 |
@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}。然后,在使用它的时候,就像注入一个一般的服务一样注入后使用即可:
1 2 3 4 5 6 7 8 9 |
public class SomeOtherServiceClass { @Autowired private UserCompositeService userService; public void doSomething() { // ..... UserDTO results = userService.getUserById(userId); // other operation... } } |