<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
server:
port: 7000
server:
port: 7002
@Slf4j
@RequestMapping("/provider")
@RestController
public class ProducerController {
@Value("${server.port}")
private String port;
// http://localhost:7000/provider/hello
@RequestMapping("/hello")
public String hello() {
log.info("provider hello! port=" + port);
return "provider hello! port=" + port;
}
}
@Slf4j
@RequestMapping("/consumer")
@RestController
public class ConsumerController {
/**
* 测试使用new的RestTemplate
* http://localhost:7002/consumer/restTemplateTest
*/
@GetMapping("/restTemplateTest")
public String restTemplateTest() {
log.info("RestTemplate invoke!");
// 此处使用直接new一个RestTemplate对象的方式
RestTemplate restTemplate = new RestTemplate();
return restTemplate.getForObject("http://localhost:7000/provider/hello", String.class);
}
}
@SpringBootApplication
public class RibbonConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(RibbonConsumerApplication.class);
}
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
@Slf4j
@RequestMapping("/consumer")
@RestController
public class ConsumerController {
@Resource
private RestTemplate restTemplate;
/**
* 测试使用Bean的RestTemplate
* http://localhost:7002/consumer/restTemplateTestUseBean
*/
@GetMapping("/restTemplateTestUseBean")
public String restTemplateTestUseBean() {
log.info("restTemplateTestUseBean invoke!");
return restTemplate.getForObject("http://localhost:7000/provider/hello", String.class);
}
}