简介
Nacos:一个更易于构建云原生应用的动态服务发现、配置管理和服务管理平台。官方网站:https://nacos.io/zh-cn/index.htmlDynamic Naming and Configuration Service,Nacos就是注册中心+配置中心的组合,可以替代Eureka做服务注册中心,替代Config+Bus做服务配置中心。
各注册中心比较
服务注册与发现框架 | CAP模型 | 控制台管理 |
---|---|---|
Eureka | AP | 支持 |
Zookeeper | CP | 不支持 |
Consul | CP | 支持 |
Nacos | AP | 支持 |
安装并运行Nacos 官网各版本下载地址https://github.com/alibaba/nacos/tags特别慢,建议找一下国内大佬们搬运的,比如1.3.2版本的https://gitee.com/myzhhc/index/tree/master/src 运行时需要安装官方给定的代表着单机模式运行方式 sh startup.sh -m standalone
3.启动服务器
Linux/Unix/Mac
启动命令(standalone代表着单机模式运行,非集群模式):
sh startup.sh -m standalone
如果您使用的是ubuntu系统,或者运行脚本报错提示[[符号找不到,可尝试如下运行:
bash startup.sh -m standalone
Windows
启动命令:
cmd startup.cmd
或者双击startup.cmd运行文件。
安装成功
单机Nacos 作为服务注册中心
所有项目的父pom.xml中添加
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>2.1.2.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
新建9001 9002服务生产者模块 以9001为例
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>zjt-cloud-api</artifactId>
<groupId>com.zjt.cloud-api</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>cloudalibaba-provider-payment9001</artifactId>
<dependencies>
<!--SpringCloud ailibaba nacos -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!-- SpringBoot整合Web组件 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!--日常通用jar包配置-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>
application.yml
server:
port: 9001
spring:
application:
name: nacos-payment-provider
cloud:
nacos:
discovery:
server-addr: localhost:8848 # 配置nacos地址
management:
endpoints:
web:
exposure:
include: '*'
主启动类和业务类
package com.zjt.cloud;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import java.util.TimeZone;
/**
* @author zjt
* @date 2020-09-21
*/
@SpringBootApplication
@EnableDiscoveryClient
public class NacosProvider9001Application {
public static void main(String[] args) {
// 时区设置
TimeZone.setDefault(TimeZone.getTimeZone("Asia/Shanghai"));
SpringApplication.run(NacosProvider9001Application.class, args);
}
}
package com.zjt.cloud.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author zjt
* @date 2020-09-21
*/
@RestController
@RequestMapping("/nacos-provider")
public class NacosProviderController {
@Value("${server.port}")
public String port;
@GetMapping("/{id}")
public String getPayment(@PathVariable Integer id) {
return "Nacos client port \t" + port + "\t id" + id;
}
}
新建 83 服务消费者模块
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>zjt-cloud-api</artifactId>
<groupId>com.zjt.cloud-api</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>cloudalibaba-consumer-order83</artifactId>
<dependencies>
<!--SpringCloud ailibaba nacos -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!--openfeign-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<!-- 引入自己定义的api通用包,可以使用Payment支付Entity -->
<dependency>
<groupId>com.zjt.cloud-api</groupId>
<artifactId>cloud-api-commons</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<!-- SpringBoot整合Web组件 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!--日常通用jar包配置-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>
application.yml
server:
port: 83
spring:
application:
name: nacos-payment-consumer
cloud:
nacos:
discovery:
server-addr: localhost:8848 # 配置nacos地址
# open feign 默认支持ribbon 超时控制交给ribbon 设置feign客户端超时时间
ribbon:
# 建立链接后从服务器读取到可用资源所用的时间
ReadTimeout: 5000
# 建立链接所用的时间,用户网络正常的情况下,两端连接所用的时间
ConnectTimeout: 5000
management:
endpoints:
web:
exposure:
include: '*'
logging:
level:
# feign日志以什么级别监控哪个接口
com.zjt.cloud.rpcserve: debug
主启动类
package com.zjt.cloud;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import java.util.TimeZone;
/**
* @author zjt
* @date 2020-09-25
*/
@EnableFeignClients
@SpringBootApplication
@EnableDiscoveryClient
public class NacosConsumer83Application {
public static void main(String[] args) {
// 时区设置
TimeZone.setDefault(TimeZone.getTimeZone("Asia/Shanghai"));
SpringApplication.run(NacosConsumer83Application.class, args);
}
}
日志配置类
package com.zjt.cloud.config;
import feign.Logger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author zjt
* @date 2020-09-25
*/
@Configuration
public class FeignLogConfig {
@Bean
Logger.Level feignLoggerLevel() {
return Logger.Level.FULL;
}
}
远程调用接口
package com.zjt.cloud.rpcserver;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
/**
* @author zjt
* @date 2020-09-25
*/
@FeignClient("nacos-payment-provider")
public interface PaymentNacosRpcServer {
@GetMapping("/nacos-provider/{id}")
String getPayment(@PathVariable("id") Integer id);
}
controller 类
package com.zjt.cloud.controller;
import com.zjt.cloud.rpcserver.PaymentNacosRpcServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author zjt
* @date 2020-09-25
*/
@RestController
@RequestMapping("/nacos-consumer")
public class NacosConsumerController {
@Autowired
private PaymentNacosRpcServer rpcServer;
@GetMapping("/{id}")
public String getPaymentInfo(@PathVariable Integer id) {
return rpcServer.getPayment(id);
}
}
测试
服务注册中心对比,Nacos支持AP 和CP 模式的切换,C是所有节点在同一时间的数据是一致的,而A定义的是所有的请求都会收到响应。AP和CP模式的选择:一般来说,如果不需要存储服务级别的信息且服务实例是通过nacos-client注册,并且能够保持心跳上报,那么就可以选择AP模式,当前spring cloud微服务是适用于AP模式的,AP模式为了服务的可用性减弱了一致性,AP模式下仅支持注册临时实例。如果需要在服务级别编辑或存储配置信息,那么需要使用CP模式,K8S服务和DNS服务则适用于CP模式。CP模式下支持注册持久化实例,此时是以Raft协议为集群运行模式,该模式下注册实例之前必须注册服务,服务不存在会返回错误信息。
Nacos 默认支持的是CAP原则中的AP原则,也可以切换成为CPcurl -X PUT '$NACOS_SERVER:8848/nacos/v1/ns/operator/switches?entry=serverMode&value=CP'
单机Nacos 作为服务配置中心 – 基础配置
Nacos 作为配置中心–基础配置 新建 cloudalibaba-config-nacos-client3377模块
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>zjt-cloud-api</artifactId>
<groupId>com.zjt.cloud-api</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>cloudalibaba-config-nacos-client3377</artifactId>
<dependencies>
<!--nacos-config-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
<!--nacos-discovery-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!--web + actuator-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!--一般基础配置-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>
application.yml和bootstrap.yml
application.yml
spring:
profiles:
active: dev # 表示开发环境
#active: test # 表示测试环境
#active: info Nacos同spring cloud config 一样,在项目初始化时,
# 需要保证先从配置中心进行配置拉取,拉取配置之后才能保证项目的正常启动 bootstrap优先级高于application
bootstrap.yml
# nacos配置
server:
port: 3377
spring:
application:
name: nacos-config-client
cloud:
nacos:
discovery:
server-addr: localhost:8848 #Nacos服务注册中心地址
config:
server-addr: localhost:8848 #Nacos作为配置中心地址
file-extension: yaml #指定yaml格式的配置
# ${spring.application.name}-${spring.profile.active}.${spring.cloud.nacos.config.file-extension}
# nacos-config-client-dev.yaml
# nacos-config-client-test.yaml ----> config.info
主启动类
package com.zjt.cloud;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import java.util.TimeZone;
/**
* @author zjt
* @date 2020-09-25
*/
@SpringBootApplication
@EnableDiscoveryClient
public class NacosConfigClient3377Application {
public static void main(String[] args) {
// 时区设置
TimeZone.setDefault(TimeZone.getTimeZone("Asia/Shanghai"));
SpringApplication.run(NacosConfigClient3377Application.class, args);
}
}
业务类
package com.zjt.cloud.controller;
import com.zjt.cloud.config.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author zjt
* @date 2020-09-25
*/
@RestController
@RequestMapping("/nacos-config")
public class NacosClientConfigController {
@Autowired
private Config config;
@GetMapping("/info")
public String getConfigInfo() {
return config.getConfigInfo();
}
}
config配置类
package com.zjt.cloud.config;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;
/**
* @author zjt
* @date 2020-09-25
*/
@Data
@Component
@RefreshScope // 动态刷新
public class Config {
@Value("${config.info}")
private String configInfo;
}
需要在Nacos配置管理中新建配置文件,注意事项https://nacos.io/zh-cn/docs/quick-start-spring-cloud.html,
启动了 Nacos server 后,您就可以参考以下示例代码,为您的 Spring Cloud 应用启动 Nacos 配置管理服务了。完整示例代码请参考:nacos-spring-cloud-config-example
添加依赖:
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
<version>${latest.version}</version>
</dependency>
注意:版本 2.1.x.RELEASE 对应的是 Spring Boot 2.1.x 版本。版本 2.0.x.RELEASE 对应的是 Spring Boot 2.0.x 版本,版本 1.5.x.RELEASE 对应的是 Spring Boot 1.5.x 版本。
在 bootstrap.properties 中配置 Nacos server 的地址和应用名
spring.cloud.nacos.config.server-addr=127.0.0.1:8848
spring.application.name=example
说明:之所以需要配置 spring.application.name ,是因为它是构成 Nacos 配置管理 dataId字段的一部分。
在 Nacos Spring Cloud 中,dataId 的完整格式如下:
${prefix}-${spring.profiles.active}.${file-extension}
prefix 默认为 spring.application.name 的值,也可以通过配置项 spring.cloud.nacos.config.prefix来配置。
spring.profiles.active 即为当前环境对应的 profile,详情可以参考 Spring Boot文档。 注意:当 spring.profiles.active 为空时,对应的连接符 - 也将不存在,dataId 的拼接格式变成 ${prefix}.${file-extension}
file-exetension 为配置内容的数据格式,可以通过配置项 spring.cloud.nacos.config.file-extension 来配置。目前只支持 properties 和 yaml 类型。
通过 Spring Cloud 原生注解 @RefreshScope 实现配置自动更新:
@RestController
@RequestMapping("/config")
@RefreshScope
public class ConfigController {
@Value("${useLocalCache:false}")
private boolean useLocalCache;
@RequestMapping("/get")
public boolean get() {
return useLocalCache;
}
}
在bootstrap.yml中配置的spring.application.name=nacos-config-client
,application.yml中指定的使用版本是 dev,我们需要在Nacos中新建的配置文件应该是nacos-config-client-dev.yaml
,文件内容
config:
info: nacos config center version = 2
测试
单机Nacos 作为服务配置中心 – 分类配置
多环境多项目管理,Nacos主页有public(保留空间),且是无法删除的。
Nacos由NameSpace、Group、Data ID 三者共同构建,类似于Java中的包名和类名。最外层的namespace是可以用于区分部署环境的,Group和DataID逻辑上区分两个目标对象
默认情况:Namespace=public,Group = DEAULT_GROUP,默认Cluster(集群)是DEDAULT。Group默认是DEAULT_GROUP,可以把不同的微服务划分到同一个分组里面去。Service就是微服务,一个Service可以包含多个Cluster(集群),Nacos默认Cluster是DEDAULT,Cluster是对指定微服务的一个虚拟划分,可以尽量让同一个集群中的微服务互相调用,以便提升性能。Instance是指微服务的实例。
三种方案加载配置,DataID方案,指定spring.profile.active和配置文件的DataID来使不同环境读取不同的配置文件
spring:
profiles:
#active: dev # 表示开发环境
active: test # 表示测试环境
#active: info Nacos同spring cloud config 一样,在项目初始化时,
# 需要保证先从配置中心进行配置拉取,拉取配置之后才能保证项目的正常启动 bootstrap优先级高于application
测试
Group方案,通过Group实现环境分区,新建分组在DEV_GROUP的配置文件
3377 项目的bootstrap.yml添加配置指定group
# nacos配置
server:
port: 3377
spring:
application:
name: nacos-config-client
cloud:
nacos:
discovery:
server-addr: localhost:8848 #Nacos服务注册中心地址
config:
server-addr: localhost:8848 #Nacos作为配置中心地址
file-extension: yaml #指定yaml格式的配置
group: DEV_GROUP
# ${spring.application.name}-${spring.profile.active}.${spring.cloud.nacos.config.file-extension}
# nacos-config-client-dev.yaml
# nacos-config-client-test.yaml ----> config.info
测试
新建命名空间并添加配置文件
3377 项目的bootstrap.yml添加命名空间namespace配置,需要注意配置的是命名空间的id
# nacos配置
server:
port: 3377
spring:
application:
name: nacos-config-client
cloud:
nacos:
discovery:
server-addr: localhost:8848 #Nacos服务注册中心地址
config:
server-addr: localhost:8848 #Nacos作为配置中心地址
file-extension: yaml #指定yaml格式的配置
group: DEV_GROUP
namespace: 87731026-6812-41e4-90ad-44e88f4ee81a # 命名空间id
# ${spring.application.name}-${spring.profile.active}.${spring.cloud.nacos.config.file-extension}
# nacos-config-client-dev.yaml
# nacos-config-client-test.yaml ----> config.info
测试