三种方式访问服务
URL 写死,用new RestTemplate()访问url来获取消息。(在服务有多个节点,地址多个的情况下,该方法不适用)
使用loadBlancerClient获取到url,然后使用new RestTemplate()访问url来获取消息。(太繁琐了)
利用@LoadBlanced 注解restTemplate,然后restTemplate 就可以使用应用名称来访问。
# product.yml spring: application: name: product datasource: driver-class-name: com.mysql.jdbc.Driver username: root password: 123456 url: jdbc:mysql://127.0.0.1:3306/SpringCloud_Sell?characterEncoding=utf-8&useSSL=false jpa: show-sql: true eureka: client: service-url: defaultZone: http://localhost:8761/eureka/
package com.imooc.product.controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class ServerController { @GetMapping("/msg") public String msg() { return "this is product' msg"; } }
package com.imooc.order.controller; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; @RestController @Slf4j public class ClientController { // @Autowired // private LoadBalancerClient loadBalancerClient; @Autowired private RestTemplate restTemplate; @GetMapping("/getProductMsg") public String getProductMsg() { //1.第一种方式(直接使用restTemplate, url写死) // RestTemplate restTemplate = new RestTemplate(); // String response = restTemplate.getForObject("http://localhost:8080/msg", String.class); //2. 第二种方式(利用loadBalancerClient通过应用名获取url, 然后再使用restTemplate) // RestTemplate restTemplate = new RestTemplate(); // ServiceInstance serviceInstance = loadBalancerClient.choose("PRODUCT"); // String url = String.format("http://%s:%s", serviceInstance.getHost(), serviceInstance.getPort()) + "/msg"; // String response = restTemplate.getForObject(url, String.class); //3. 第三种方式(利用@LoadBalanced, 可在restTemplate里使用应用名字) String response = restTemplate.getForObject("http://PRODUCT/msg", String.class); log.info("response={}", response); return response; } }
// 第三种情况 package com.imooc.order.config; import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.context.annotation.Bean; import org.springframework.stereotype.Component; import org.springframework.web.client.RestTemplate; @Component public class RestTemplateConfig { @Bean @LoadBalanced public RestTemplate restTemplate() { return new RestTemplate(); } }