1. 创建可调用接口

在provider项目里创建controller层
image.png

  1. @RestController
  2. public class ProviderController {
  3. //SPEL
  4. @Value("${server.port}")
  5. private String port;
  6. @GetMapping("/index")
  7. public String index(){
  8. return this.port;
  9. }
  10. }

2. 创建调用接口

在consumer创建调用接口

  1. package com.jili.controller;
  2. import lombok.extern.slf4j.Slf4j;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.cloud.client.ServiceInstance;
  5. import org.springframework.cloud.client.discovery.DiscoveryClient;
  6. import org.springframework.web.bind.annotation.GetMapping;
  7. import org.springframework.web.bind.annotation.RestController;
  8. import org.springframework.web.client.RestTemplate;
  9. import java.util.List;
  10. import java.util.concurrent.ThreadLocalRandom;
  11. @RestController
  12. @Slf4j
  13. public class ConsumerController {
  14. //自动装载
  15. @Autowired
  16. private DiscoveryClient discoveryClient;
  17. @Autowired
  18. private RestTemplate restTemplate;
  19. @GetMapping("/instances")
  20. public List<ServiceInstance> instance(){
  21. List<ServiceInstance> provider = this.discoveryClient.getInstances("provider");
  22. return provider;
  23. }
  24. @GetMapping("/index")
  25. public String index(){
  26. //调用provider服务的index的方法
  27. //1.找到provider实例
  28. List<ServiceInstance> list = this.discoveryClient.getInstances("provider");
  29. int index = ThreadLocalRandom.current().nextInt(list.size());
  30. ServiceInstance serviceInstance = list.get(index);
  31. String url = serviceInstance.getUri()+ "/index";
  32. //2.调用
  33. log.info("调用端口:{}",serviceInstance.getPort());
  34. return "调用了端口为:"+serviceInstance.getPort()+"的服务,返回结果为:"+this.restTemplate.getForObject(url,String.class)+"地址为:"+url;
  35. }
  36. }

通过restTemplate来访问nacos实例中provider服务的接口来模拟服务调用

由于restTemplate没有注入的问题,可以创建配置类来注入
image.png

  1. package com.jili.config;
  2. import org.springframework.context.annotation.Bean;
  3. import org.springframework.context.annotation.Configuration;
  4. import org.springframework.web.client.RestTemplate;
  5. @Configuration
  6. public class ConsumerConfig {
  7. @Bean
  8. public RestTemplate restTemplate(){
  9. return new RestTemplate();
  10. }
  11. }

也可以在启动类里直接注入,如:
image.png

3.效果

image.png


ps:为什么可以在*启动类直接注入?

@SpringBootApplication注解里包含了
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan
image.png
而@SpringBootConfiguration本质上也就是@Configuration~
image.png