|
| 1 | +package cn.iocoder.springcloudalibaba.labx22.consumerdemo; |
| 2 | + |
| 3 | +import org.springframework.beans.factory.annotation.Autowired; |
| 4 | +import org.springframework.boot.SpringApplication; |
| 5 | +import org.springframework.boot.autoconfigure.SpringBootApplication; |
| 6 | +import org.springframework.cloud.client.ServiceInstance; |
| 7 | +import org.springframework.cloud.client.discovery.DiscoveryClient; |
| 8 | +import org.springframework.cloud.client.loadbalancer.LoadBalancerClient; |
| 9 | +import org.springframework.context.annotation.Bean; |
| 10 | +import org.springframework.context.annotation.Configuration; |
| 11 | +import org.springframework.web.bind.annotation.GetMapping; |
| 12 | +import org.springframework.web.bind.annotation.RestController; |
| 13 | +import org.springframework.web.client.RestTemplate; |
| 14 | + |
| 15 | +import java.util.List; |
| 16 | + |
| 17 | +@SpringBootApplication |
| 18 | +// @EnableDiscoveryClient |
| 19 | +public class DemoConsumerApplication { |
| 20 | + |
| 21 | + public static void main(String[] args) { |
| 22 | + SpringApplication.run(DemoConsumerApplication.class, args); |
| 23 | + } |
| 24 | + |
| 25 | + @Configuration |
| 26 | + public class RestTemplateConfiguration { |
| 27 | + |
| 28 | + @Bean |
| 29 | + public RestTemplate restTemplate() { |
| 30 | + return new RestTemplate(); |
| 31 | + } |
| 32 | + |
| 33 | + } |
| 34 | + |
| 35 | + @RestController |
| 36 | + static class TestController { |
| 37 | + |
| 38 | + @Autowired |
| 39 | + private DiscoveryClient discoveryClient; |
| 40 | + @Autowired |
| 41 | + private RestTemplate restTemplate; |
| 42 | + @Autowired |
| 43 | + private LoadBalancerClient loadBalancerClient; |
| 44 | + |
| 45 | + @GetMapping("/hello") |
| 46 | + public String hello(String name) { |
| 47 | + // 获得服务 `demo-provider` 的一个实例 |
| 48 | + ServiceInstance instance; |
| 49 | + if (true) { |
| 50 | + // 获取服务 `demo-provider` 对应的实例列表 |
| 51 | + List<ServiceInstance> instances = discoveryClient.getInstances("demo-provider"); |
| 52 | + // 选择第一个 |
| 53 | + instance = instances.size() > 0 ? instances.get(0) : null; |
| 54 | + } else { |
| 55 | + instance = loadBalancerClient.choose("demo-provider"); |
| 56 | + } |
| 57 | + // 发起调用 |
| 58 | + if (instance == null) { |
| 59 | + throw new IllegalStateException("获取不到实例"); |
| 60 | + } |
| 61 | + String targetUrl = instance.getUri() + "/echo?name=" + name; |
| 62 | + String response = restTemplate.getForObject(targetUrl, String.class); |
| 63 | + // 返回结果 |
| 64 | + return "consumer:" + response; |
| 65 | + } |
| 66 | + |
| 67 | + } |
| 68 | + |
| 69 | +} |
0 commit comments