配置Bean
@Configuration
public class RestTemplateConfig{
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
服务调用
@RestController
public class RestTemplateController {
@Autowired
RestTemplate restTemplate;
/**
* 如果服务是注册到注册中心的,那么两种url访问方式都可以。
* 1:http://应用程序名称/hello
* 2:http://ip:port/hello
*
*/
@GetMapping("/hello")
public String hello() {
return "[RestTemplate]" + restTemplate.getForObject("http://应用程序名称/hello", String.class);
}
}
该博客介绍了如何在Spring Boot中配置`RestTemplate`以实现负载均衡。通过`@Configuration`和`@Bean`注解创建了一个加载平衡的`RestTemplate`实例。在服务调用部分,展示了如何在`RestController`中注入并使用`RestTemplate`,通过`http://应用程序名称/hello`这样的服务发现方式来调用其他服务。
1583

被折叠的 条评论
为什么被折叠?



