服务引用RestTemplate

2018-08-19  本文已影响0人  Nick_4438

前言

本文介绍如何调用服务,调用服务有如下方法:

RestTemplate

 //1.第一种方式,写死地址
RestTemplate restTemplate = new RestTemplate();
String response =  restTemplate.getForObject("http://localhost:8080/msg",String.class);

LoadBalancerClient

@RestController
@Slf4j
public class ClientController {
    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @GetMapping("/getProductMsg")
    public String getProductMsg(){   
        //2.第二种,通过应用名获url,然后再使用第一种方式处理
        RestTemplate restTemplate = new RestTemplate();
        ServiceInstance serviceInstance = loadBalancerClient.choose("PRODUCT");
        String url = String.format("http://%s:%d/msg",serviceInstance.getHost(),serviceInstance.getPort());
        String response =  restTemplate.getForObject(url,String.class);
        log.info("resoponse={}",response);
        return  response;
    }
}

使用LoadBalanced注解

package com.nick.order.config;
@Component
public class RestTemplateConfig {

    @Bean
    @LoadBalanced
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }
}
package com.nick.order.controller;

@RestController
@Slf4j
public class ClientController {

    @Autowired
    private RestTemplate restTemplate;


    @GetMapping("/getProductMsg")
    public String getProductMsg() {
        String response =  restTemplate.getForObject("http://PRODUCT/msg",String.class);
        log.info("resoponse={}", response);
        return response;
    }
}
上一篇下一篇

猜你喜欢

热点阅读