安裝Nacos
-
下載二進(jìn)制包
-
解壓
unzip nacos-server-1.0.0.zip cd nacos/bin -
啟動(dòng)
sh startup.sh -m standalone -
打開登陸地址
http://localhost:8848/nacos/
添加Spring Cloud Alibaba依賴
<dependencyManagement>
<dependencies>
<!--spring-boot-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>2.1.2.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!-- spring-cloud -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Greenwich.SR2</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!-- spring-cloud-alibaba -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>2.1.0.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--nacos注冊(cè)中心-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
</dependencies>
編寫服務(wù)提供者
@RestController
@EnableDiscoveryClient
@SpringBootApplication
public class NacosDiscoveryProviderApplication {
public static void main(String[] args) {
SpringApplication.run(NacosDiscoveryProviderApplication.class, args);
}
@GetMapping("/hello")
public String hello(){
return "hello nacos-discovery-provider";
}
}
配置注冊(cè)到Nacos
server:
port: 8085
spring:
application:
name: nacos-discovery-provider
cloud:
nacos:
discovery:
server-addr: 127.0.0.1:8848
看到日志
2020-10-10 23:14:10.152 INFO 54121 --- [ main] c.a.c.n.registry.NacosServiceRegistry : nacos registry, nacos-discovery-provider 192.168.0.105:8085 register finished
表示已經(jīng)成功注冊(cè)到nacos,如圖:

nacos注冊(cè)服務(wù)者
編寫消費(fèi)者代碼
@RestController
@EnableDiscoveryClient
@SpringBootApplication
public class NacosDiscoveryConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(NacosDiscoveryConsumerApplication.class, args);
}
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
使用Ribbon做客戶端負(fù)載均衡調(diào)用服務(wù)者
@RestController
public class HelloController {
@Autowired
RestTemplate restTemplate;
@Autowired
LoadBalancerClient loadBalancerClient;
@GetMapping("/hello")
public String HelloClient(String name){
ServiceInstance serviceInstance = loadBalancerClient.choose("nacos-discovery-provider");
URI uri = serviceInstance.getUri();
return restTemplate.getForObject(uri + "hello?name=" + name, String.class);
}
}
配置文件與服務(wù)端類似
server:
port: 18085
spring:
application:
name: nacos-discovery-consumer
cloud:
nacos:
discovery:
server-addr: 127.0.0.1:8848
兩者都成功注冊(cè)到Nacos里

image-20201011102305466
調(diào)用消費(fèi)者/hello服務(wù),可以調(diào)用Provider提供的服務(wù)

image-20201011102401045