安装Nacos
-
下载二进制包
-
解压
unzip nacos-server-1.0.0.zip cd nacos/bin
-
启动
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注册中心-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
</dependencies>
编写服务提供者
@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";
}
}
配置注册到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
表示已经成功注册到nacos,如图:
nacos注册服务者编写消费者代码
@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做客户端负载均衡调用服务者
@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);
}
}
配置文件与服务端类似
server:
port: 18085
spring:
application:
name: nacos-discovery-consumer
cloud:
nacos:
discovery:
server-addr: 127.0.0.1:8848
两者都成功注册到Nacos里
image-20201011102305466调用消费者/hello服务,可以调用Provider提供的服务
image-20201011102401045
网友评论