Spring Boot+Cloud RestTemplate 调用IP或域名

RestTemplate如果生成Bean的时候加了@LoadBalanced注解,则不能在请求路径里写ip,必须写服务名称service_id


@Bean
@LoadBalanced
RestTemplate restTemplate(){
   return new RestTemplate();
}
@RequestMapping("/getOrder")
public String order(){
    String url="http://clmember/getMember";
    String result = restTemplate.getForObject(url, String.class);
    return "cl-order  "+result;
}

要想在请求路径里写ip地址和端口,不能使用 @LoadBalanced

@SpringBootApplication
@EnableEurekaClient
public class ClOrderApplication {

   public static void main(String[] args) {
      SpringApplication.run(ClOrderApplication.class, args);
   }

//restTemplate调用远程服务
   @Bean
   RestTemplate restTemplate(){
      return new RestTemplate();
   }
}
@RestController
public class OrderController {

    @Autowired
    private RestTemplate restTemplate;//springboot web提供,默认没有注入springboot容器
    /**
     * Springcloud的两种调用方式,Rest,Feign
     * @return
     */
    @RequestMapping("/getOrder")
    public String order(){
        String result = restTemplate.getForObject("http://localhost:8080/getMember", String.class);
        return "cl-order  "+result;
    }
}

参考:https://www.jianshu.com/p/0db3570e4674

你可能感兴趣的:(Springcloud)