Nacos(2)~消费者
作者:互联网
创建消费者项目01-spa-nacos-consumer
01-spa-nacos-consumer为00-spa-parent的项目子项目需要
<parent>
<groupId>com.cy</groupId>
<artifactId>00-spa-parent</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
</dependencies>
修改配置文件application.yml
server:
port: 8090 # 指定端口
spring:
application:
name: nacos-consumer # 给服务起个名字
说明:消费者虽然没有注册nacos,但是添加了nacos依赖,会自动自注册
创建启动类
@SpringBootApplication
public class NacosConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(NacosConsumerApplication.class,args);
}
@Autowired
private RestTemplate restTemplate;
/**初始化RestTemplate对象(Spring提供)*/
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
@Autowired
private LoadBalancerClient loadBalancerClient;
@Value("${spring.application.name}")
private String applicationName;
@RestController
public class ConsumerController{
@GetMapping("/consumer/doRestEcho/")
public String doRestEcho(){
// url写的不灵活
// String url="http://localhost:8081/provider/echo/"+applicationName;
// 根据服务名查找服务
ServiceInstance serviceinstance = loadBalancerClient.choose("nacos-provider");
String host=serviceinstance.getHost();
Integer port=serviceinstance.getPort();
// String url="http://"+host+":"+port+"/provider/echo/"+applicationName;
String url = String.format("http://%s:%s/provider/echo/%s",
serviceinstance.getHost(),
serviceinstance.getPort(),
applicationName);
return restTemplate.getForObject(url,String.class);
// return applicationName+"-> :consumer echo";
// return url;
}
}
}
标签:applicationName,String,url,nacos,Nacos,serviceinstance,public,消费者 来源: https://blog.csdn.net/weixin_48621005/article/details/115532374