1.在引导类中创建RestTemplate的Spring实例
@SpringBootApplication @EnableEurekaClient public class EurekaUserApplication { public static void main(String[] args) { SpringApplication.run(EurekaUserApplication.class,args); } @Bean public RestTemplate restTemplate(){ return new RestTemplate(); } }
2.在调用类中引入restTemplate,使用restTemplate.getForObject()方法,调用其他服务接口
@RestController @RequestMapping("/user") public class UserController { @Autowired private RestTemplate restTemplate; @GetMapping("/findOrdersByUser/{id}") public String findOrdersByUser(@PathVariable String id){ int oid=123; return restTemplate.getForObject("http://localhost:7900/order/"+oid,String.class); } }
这里restTemplate.getForObject("http://localhost:7900/order/"+oid,String.class);,使用的是“ip+端口号”的形式,也可以使用restTemplate.getForObject("服务实例名称",参数)方式,便于后期维护。