1. 创建可调用接口
在provider项目里创建controller层
@RestController
public class ProviderController {
//SPEL
@Value("${server.port}")
private String port;
@GetMapping("/index")
public String index(){
return this.port;
}
}
2. 创建调用接口
在consumer创建调用接口
package com.jili.controller;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
@RestController
@Slf4j
public class ConsumerController {
//自动装载
@Autowired
private DiscoveryClient discoveryClient;
@Autowired
private RestTemplate restTemplate;
@GetMapping("/instances")
public List<ServiceInstance> instance(){
List<ServiceInstance> provider = this.discoveryClient.getInstances("provider");
return provider;
}
@GetMapping("/index")
public String index(){
//调用provider服务的index的方法
//1.找到provider实例
List<ServiceInstance> list = this.discoveryClient.getInstances("provider");
int index = ThreadLocalRandom.current().nextInt(list.size());
ServiceInstance serviceInstance = list.get(index);
String url = serviceInstance.getUri()+ "/index";
//2.调用
log.info("调用端口:{}",serviceInstance.getPort());
return "调用了端口为:"+serviceInstance.getPort()+"的服务,返回结果为:"+this.restTemplate.getForObject(url,String.class)+"地址为:"+url;
}
}
通过restTemplate来访问nacos实例中provider服务的接口来模拟服务调用
由于restTemplate没有注入的问题,可以创建配置类来注入
package com.jili.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
public class ConsumerConfig {
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
也可以在启动类里直接注入,如:
3.效果
ps:为什么可以在*启动类直接注入?
@SpringBootApplication注解里包含了
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan
而@SpringBootConfiguration本质上也就是@Configuration~