上一節我們在nacos上注冊了服務,這一節我們嘗試去調用該服務。
1、前提約束
- 已經在nacos上注冊了一個服務
2、操作步驟
- 創建一個springboot項目,加入以下依賴:
<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>
注意:筆者使用的spring-boot版本是2.3.7.RELEASE,spring-cloud-alibaba版本是2.2.2.RELEASE
- 修改application.properties:
spring.application.name=nacos-consumer
spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848
server.port=10002
- 在主啟動類同級目錄下創建一個配置類:
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 NacosConfig {
@LoadBalanced
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
- 在主啟動類同級目錄下創建入口類:
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;
@RestController
public class TestController {
@Resource
private RestTemplate restTemplate;
@GetMapping("/test")
public String test(){
return restTemplate.getForObject("http://nacos-provider/get", String.class);
}
}
- 啟動項目,訪問http://localhost:10002/test,便能看到效果。
以上就是nacos遠程調用的過程。