美文网首页
RestTemplate三种使用方式

RestTemplate三种使用方式

作者: 蓝色_fea0 | 来源:发表于2018-08-22 18:00 被阅读25次

方式1:

向eurekaServer上注册了两个服务
client1: 9611
client2: 9612


image.png

client1代码:

package com.wuhongyu.eurekaclient.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Slf4j
public class TestController {

    @GetMapping("/test1")
    public String test1(){
        return "success";
    }
}

client2代码:

package com.wuhongyu.eurekaclient2.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
@Slf4j
public class TestController {

    @GetMapping("/getClient1Test1")
    public String getClient1Test1(){
        RestTemplate restTemplate = new RestTemplate();
        String url = "http://localhost:9611/test1";
        String response = restTemplate.getForObject(url, String.class);
        log.info("response={}",response);
        return response;
    }
}

请求结果:

image.png
image.png

方式2:

client2代码:

  @Autowired
    private LoadBalancerClient loadBalancerClient;

    @GetMapping("/getClient1Test2")
    public String getClient1Test2(){
        RestTemplate restTemplate = new RestTemplate();
        ServiceInstance client1 = loadBalancerClient.choose("CLIENT1");
        String url = String.format("http://%s:%s/test1", client1.getHost(), client1.getPort());
        String response = restTemplate.getForObject(url, String.class);
        log.info("response={}",response);
        return response;
    }

方式3:
client2中增一个类: BeanConfig

import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

@Configuration
public class BeanConfig {

    @Bean
    @LoadBalanced
    public RestTemplate getRestTemplate(){
        return new RestTemplate();
    }
}

代码:

 @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/getClient1Test3")
    public String getClient1Test3(){
        String url = "http://CLIENT1/test1";
        String response = restTemplate.getForObject(url, String.class);
        log.info("response={}",response);
        return response;
    }

相关文章

网友评论

      本文标题:RestTemplate三种使用方式

      本文链接:https://www.haomeiwen.com/subject/cemyiftx.html