SpringCloud服务间的调用有两种方式:RestTemplate和FeignClient。不管是什么方式,他都是通过REST接口调用服务的http接口,参数和结果默认都是通过jackson序列化和反序列化。因为SpringMVC的RestController定义的接口,返回的数据都是通过Jackson序列化成JSON数据。
一、RestTemplate
使用这种方式,只需要定义一个RestTemplate的Bean,设置成LoadBalanced即可。
如下示例:
@Configuration publicclassSomeCloudConfiguration{ @LoadBalanced @Bean RestTemplaterestTemplate(){ returnnewRestTemplate(); } }这样我们就可以在需要用的地方注入这个bean使用:
publicclassSomeServiceClass{ @Autowired privateRestTemplaterestTemplate; publicStringgetUserById(LonguserId){ UserDTOresults=restTemplate.getForObject("http://users/getUserDetail/"+userId,UserDTO.class); returnresults; } }其它示例参考:
@SpringBootApplication publicclassSleuthClientApplication{ @Bean publicRestTemplaterestTemplate(){ returnnewRestTemplate(); } publicstaticvoidmain(String[]args){ SpringApplication.run(SleuthClientApplication.class,args); } } @RestController classHomeController{ privatestaticfinalLoglog=LogFactory.getLog(HomeController.class); @Autowired privateRestTemplaterestTemplate; privateStringurl="http://localhost:9986"; @RequestMapping("/service1") publicStringservice1()throwsException{ log.info("service1"); Thread.sleep(200L); Strings=this.restTemplate.getForObject(url+"/service2",String.class); returns; } }二、FeignClient
除了上面的方式,我们还可以用FeignClient。
@FeignClient(value="users",path="/users") publicinterfaceUserCompositeService{ @RequestMapping(value="/getUserDetail/{id}", method=RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE) UserDTOgetUserById(@PathVariableLongid); }我们只需要使用@FeignClient定义一个接口,SpringCloudFeign会帮我们生成一个它的实现,从相应的users服务获取数据。
其中,@FeignClient(value=“users”,path=“/users/getUserDetail”)里面的value是服务ID,path是这一组接口的path前缀。在下面的方法定义里,就好像设置SpringMVC的接口一样,对于这个方法,它对应的URL是/users/getUserDetail/{id}。然后,在使用它的时候,就像注入一个一般的服务一样注入后使用即可:
publicclassSomeOtherServiceClass{ @Autowired privateUserCompositeServiceuserService; publicvoiddoSomething(){ //..... UserDTOresults=userService.getUserById(userId); //otheroperation... } }其中遇到的坑请参见:http://dockone.io/article/2140
本文内容总结:
原文链接:https://www.cnblogs.com/moonandstar08/p/7565524.html