一、Nacos
Dynamic Naming and Configuration Service,Na为naming/nameServer即注册中心,co为configuration即注册中心,service是指该注册/配置中心都是以服务为核心。Nacos是阿里开源项目,集配置和服务注册于一体,Consul注册中心同样具有注册和配置功能一体,但从使用体验上Nacos使用更加简单,容易。
官网地址:http://nacos.io/
配置中心数据模型见下图,其主要包括命名空间,组,服务三级,同一命名空间下可以有多个组,同一组下可以有多个服务。
配置中心支持配置热加载,任何配置更新都会被及时加载到服务中,nacos配置客户端服务以长连接方式连接到nocos配置中心,以固定频率(测试显示频率是30s,原理上是等待了29.5s后发起配置查询和对比)进行配置拉取和对比,若更新,则及时刷新内存中的配置。
注册中心包括服务注册和服务发现。
服务注册的策略的是每5秒向nacos server发送一次心跳,心跳带上了服务名,服务ip,服务端口等信息。同时 nacos server也会向client 主动发起健康检查,支持tcp/http检查。如果15秒内无心跳且健康检查失败则认为实例不健康,如果30秒内健康检查失败则剔除实例。
服务发现的一般流程是先从注册中心获取到服务的实例列表,然后再根据自身的需求,来选择其中的部分实例或者按照一定的流量分配机制来访问不同的服务提供者。实际实现方式有客户端负载和服务端负载两种方式。nacos采用服务端负载方式,区别于客户端负载,这样能实现更多的对服务提供者的控制。
客户端负载原理图:
服务端负载原理图:
对比两种不同实现方式,服务端的负载均衡,给服务提供者更强的流量控制权,但是无法满足不同的消费者希望使用不同负载均衡策略的需求。而不同负载均衡策略的场景,确实是存在的。而客户端的负载均衡则提供了这种灵活性,并对用户扩展提供更加友好的支持。但是客户端负载均衡策略如果配置不当,可能会导致服务提供者出现热点,或者压根就拿不到任何服务提供者。
二、安装启动nacos
参考:Nacos 快速开始
git安装方式:
git clone https://github.com/alibaba/nacos.git //最新版本1.3
cd nacos/
mvn -Prelease-nacos clean install -U -Dmaven.test.skip=true //打包, 需要下载依赖包,安装过程中git下载会比较慢,耐心等待一下。
cd distribution/
sh bin/startup.sh -m standalone //居然启动失败了
cp nacos-server-1.3.0/nacos/target/nacos-server.jar . //坑1
sh bin/startup.sh -m standalone //成功了
发行包安装方式:
下载地址
下载解压,按照上述启动方式直接启动, 我采用了这种方式,nacos版本:1.1.4
配置mysql持久化
前提:已经有mysql数据库
步骤一:按照conf/nacos-mysql.sql初始化数据库
步骤二:修改application.properties如下
server.contextPath=/nacos
server.servlet.contextPath=/nacos
server.port=8848
spring.datasource.platform=mysql
db.num=1
db.url.0=jdbc:mysql://127.0.0.1:3306/nacos?characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true
db.user=root
db.password=${your mysql password}
步骤三:重启nacos
步骤四:看效果
登录, 默认用户密码都是nacos:http://127.0.0.1:8848/nacos/#/login
三、项目测试
这里使用之前项目基础上测试nacos,其中一些依赖并非本项目所必须。主要是nacos-provider,nacos-consumer,nacos-client三个项目。下面代码结构详细贴出,以便copy下来就能够正确执行,项目结构如下:
3.1 nacos配置
新增nacos配置
增加配置项
注意dataId为配置文件名称,为完整的配置文件,包括文件后缀名。这里单独制定了group为:CLARK_GROUP
3.2 parent pom.xml
其中有版本对应问题,参考:https://github.com/alibaba/spring-cloud-alibaba/wiki/版本说明
<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">
<modelVersion>4.0.0</modelVersion>
<groupId>cn.com.spring</groupId>
<artifactId>clark-parent</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>pom</packaging>
<name>clark-parent</name>
<url>http://maven.apache.org</url>
<repositories>
<repository>
<id>central</id>
<name>aliyun maven</name>
<url>http://maven.aliyun.com/nexus/content/groups/public/</url>
<layout>default</layout>
<!-- 是否开启发布版构件下载 -->
<releases>
<enabled>true</enabled>
</releases>
<!-- 是否开启快照版构件下载 -->
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<modules>
<module>clark-nacos-provider</module>
<module>clark-nacos-consumer</module>
<module>clark-nacos-client</module>
</modules>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.2.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<commons.version>3.4</commons.version>
<spring-cloud.version>Finchley.RELEASE</spring-cloud.version>
<spring-cloud-alibaba-dependency.version>2.0.2.RELEASE</spring-cloud-alibaba-dependency.version>
<!-- alibaba and pringcloud version map: https://github.com/alibaba/spring-cloud-alibaba/wiki/%E7%89%88%E6%9C%AC%E8%AF%B4%E6%98%8E -->
</properties>
<dependencies>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>${spring-cloud-alibaba-dependency.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
<version>2.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.56</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons.version}</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.9</version>
</dependency>
<dependency>
<groupId>com.alibaba.boot</groupId>
<artifactId>dubbo-spring-boot-starter</artifactId>
<version>0.2.0</version>
</dependency>
<dependency>
<groupId>com.caucho</groupId>
<artifactId>hessian</artifactId>
<version>4.0.7</version>
</dependency>
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson</artifactId>
<version>3.11.5</version>
</dependency>
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson-spring-boot-starter</artifactId>
<version>3.11.5</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>2.1.1.RELEASE</version>
</dependency>
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-core</artifactId>
<version>1.7.1</version>
</dependency>
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-annotation-aspectj</artifactId>
<version>1.7.1</version>
</dependency>
<dependency>
<groupId>com.github.shalousun</groupId>
<artifactId>common-util</artifactId>
<version>1.9.4</version>
</dependency>
<dependency>
<groupId>com.alexecollins.docker</groupId>
<artifactId>docker-maven-plugin</artifactId>
<version>2.9.3</version>
<type>maven-plugin</type>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<distributionManagement>
<repository>
<id>maven-ali</id>
<url>http://maven.aliyun.com/nexus/content/groups/public//</url>
</repository>
</distributionManagement>
</project>
3.3 nacos-provider
pom.xml
<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">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>cn.com.spring</groupId>
<artifactId>clark-parent</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>clark-nacos-provider</artifactId>
<name>clark-nacos-provider</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<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>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
<dependency> <!-- 引入log4j2依赖 -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>clark-nacos-provider</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration><useSystemClassLoader>false</useSystemClassLoader>
</configuration>
</plugin>
</plugins>
</build>
</project>
bootstrap.xml
server:
name: nacos-provider
port: 9096
spring:
application:
name: nacos-provider
cloud:
nacos:
discovery:
server-addr: 127.0.0.1:8848
config:
server-addr: 127.0.0.1:8848
namespace: ba49f568-2495-4a7b-b957-cd8e1d7077fa
group: CLARK-GROUP
file-extension: yml
#// nacos配置默认使用使用public namespace和DEFAULT_GROUP,不需要显示填写,填写则会报错。坑2
#// 配置类型支持test,yaml,properties等,如果文件是yml结尾,则需要配置file-extension: yml
feign:
hystrix:
enabled: true
hystrix:
command:
default:
execution.isolation.thread.timeoutInMilliseconds: 60000
ribbon:
ConnectTimeout: 6000
ReadTimeout: 10000
logging:
config: classpath:log4j2.xml
level:
cn.jay.repository: trace
3.4 代码测试 nacos-provider
测试读取配置文件,测试热更新@RefreshScope
package cn.com.spring.clark.server.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
@RefreshScope
@ConfigurationProperties(prefix = "student")
public class StudentConfig {
private String name;
private int age;
private String sex;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
@Override
public String toString() {
return "StudentConfig{" + "name='" + name + '\'' + ", age=" + age + ", sex='" + sex + '\'' + '}';
}
}
简单的服务方法
package cn.com.spring.clark.server.service.impl;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;
import cn.com.spring.clark.server.service.ProviderService;
@RefreshScope
@Service
public class ProviderServiceImpl implements ProviderService {
@Value("${zookeeperStr}")
private String zookeeperStr;
@Override
public String sayHello(String name) {
// TODO Auto-generated method stub
return "hello:"+name;
}
@Override
public String getZookeeperAddr() {
// TODO Auto-generated method stub
return zookeeperStr;
}
}
服务类
package cn.com.spring.clark.server.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import cn.com.spring.clark.server.config.StudentConfig;
import cn.com.spring.clark.server.service.ProviderService;
@Controller
public class ProviderController {
private static Logger logger = LoggerFactory.getLogger(ProviderController.class);
@Autowired
private ProviderService providerService;
@Autowired
private StudentConfig studentConfig;
@GetMapping("/sayhello")
@ResponseBody
public String sayHello(String name) {
logger.info(name);
return providerService.sayHello(name);
}
@GetMapping("/getstudent")
@ResponseBody
public Object getStudentConfig() {
logger.info(studentConfig.toString());
return studentConfig;
}
@GetMapping("/getzookeeper")
@ResponseBody
public String getZookeeper() {
logger.info("getZookeeper");
return this.providerService.getZookeeperAddr();
}
}
启动类
package cn.com.spring.clark;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.client.SpringCloudApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.scheduling.annotation.EnableScheduling;
import cn.com.spring.clark.server.config.StudentConfig;
@SpringCloudApplication
@EnableDiscoveryClient
@EnableFeignClients
@EnableScheduling
@EnableConfigurationProperties({StudentConfig.class})
public class NacosProviderApplication {
public static void main(String[] args) {
// TODO Auto-generated method stub
SpringApplication.run(NacosProviderApplication.class, args);
}
}
3.5 定义服务二方库 nacos-client
代码结构
<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">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>cn.com.spring</groupId>
<artifactId>clark-parent</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>clark-nacos-client</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
</dependencies>
</project>
package cn.com.spring.clark.nacos.client;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
@FeignClient(name="nacos-provider", fallback=NacosProviderClientHystrix.class)
public interface NacosProviderClient {
/**
* 必须加@RequestParam,否则会被转换为post请求
* @param name
* @return
*/
@RequestMapping(value="/sayhello", method = {RequestMethod.GET})
public String sayHello(@RequestParam(value = "name")String name);
}
package cn.com.spring.clark.nacos.client;
import org.springframework.stereotype.Component;
@Component
public class NacosProviderClientHystrix implements NacosProviderClient {
@Override
public String sayHello(String name) {
// TODO Auto-generated method stub
return "server error";
}
}
3.6 定义服务调用nacos-consumer
pom文件引入二方库包
<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">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>cn.com.spring</groupId>
<artifactId>clark-parent</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>clark-nacos-consumer</artifactId>
<name>clark-nacos-consumer</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<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>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
<dependency> <!-- 引入log4j2依赖 -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
<dependency>
<groupId>cn.com.spring</groupId>
<artifactId>clark-nacos-client</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>clark-nacos-consumer </finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<useSystemClassLoader>false</useSystemClassLoader>
</configuration>
</plugin>
</plugins>
</build>
</project>
bootstrap文件
server:
name: nacos-consumer
port: 9098
spring:
application:
name: nacos-consumer
cloud:
nacos:
discovery:
server-addr: 127.0.0.1:8848
config:
server-addr: 127.0.0.1:8848
namespace: ba49f568-2495-4a7b-b957-cd8e1d7077fa
group: CLARK-GROUP
file-extension: yml
feign:
hystrix:
enabled: true
hystrix:
command:
default:
execution.isolation.thread.timeoutInMilliseconds: 60000
ribbon:
ConnectTimeout: 6000
ReadTimeout: 10000
logging:
config: classpath:log4j2.xml
level:
cn.jay.repository: trace
consumer controller,调用provider的入口
package cn.com.spring.clark.nacos.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import cn.com.spring.clark.nacos.client.NacosProviderClient;
@Controller
public class ClientController {
private static Logger logger = LoggerFactory.getLogger(ClientController.class);
@Autowired
private NacosProviderClient providerClient;
@GetMapping("/sayhello")
@ResponseBody
public String sayHello(String name) {
logger.info(name);
return providerClient.sayHello(name);
}
}
启动类
package cn.com.spring.clark;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.client.SpringCloudApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.scheduling.annotation.EnableScheduling;
import cn.com.spring.clark.nacos.config.StudentConfig;
@SpringCloudApplication
@EnableDiscoveryClient
@EnableFeignClients
@EnableScheduling
@EnableConfigurationProperties({StudentConfig.class})
public class NacosConsumertApplication {
public static void main(String[] args) {
SpringApplication.run(NacosConsumertApplication.class, args);
}
}
3.7 运行测试
3.7.1配置测试:
3.7.2注册中心测试:
四、踩坑及注意事项
1、多个nacos版本启动后登陆页面会报错,切换时需要清空缓存;
2、bootstrap配置时namespace并非制定的名称,而是系统生成的一串数字串
3、配置文件名称后缀和系统默认不一致时需要指定file-extension
4、配置文件名称采用{spring.profile.active}.${file-extension},prefix:spring.application.name
5、启动时发现找不到NacosProviderClientHystrix,有两种解决办法,一是在使用二方库的项目中添加componentscan显示加载,二是让启动类处于所有包路径的顶端,也就是二方库的包路径是启动类包路径的子包。