预备环境准备
nacos-server-2.0.3
jdk1.8
mysql8+
集群搭建
1 用本地不同端口搭建集群
2 集群搭建需要启动三个以上的nacos服务端
3 在进行集群配置之前,先完成对MySQL数据源的初始化和配置
4 Nginx配置upstream实现负载均衡
新增cluster.conf集群配置,配置如下
192.168.0.113:8850
192.168.0.113:8860
192.168.0.113:8870
Mysql执行nacos-mysql.sql 新建nacos 数据库
修改application.properties 数据库连接
### If use MySQL as datasource:
spring.datasource.platform=mysql
### Count of DB:
db.num=1
### Connect URL of DB:
db.url.0=jdbc:mysql://127.0.0.1:3306/nacos?characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC
db.user.0=root
db.password.0=123456
copy3份nacos 服务端 并修改端口
分别启动3个nacos 服务端 、/bin/startup.cmd
注:集群启动报错问题(Error creating bean with name ‘grpcSdkServer‘)
因为在Nacos2.0以后,相对于之前的版本增加了grgc的通信方式,简单来说 8801端口占用的偏移量是9801端口和9802端口、8802端口占用的偏移量是9802端口和9803端口、8803端口占用的偏移量是9803端口和9804端口,端口冲突了。
修改为:8850、8860、8870
Nginx配置upstream实现负载均衡
注:新版本nacos 好像提供了负载均衡
Nginx可以配置代理多台服务器,当一台服务器宕机之后,仍能保持系统可用。
- 在http节点下,添加upstream节点。
upstream cluster {
server 127.0.0.1:8850;
server 127.0.0.1:8860;
server 127.0.0.1:8870;
}
- 将server节点下的location节点中的proxy_pass配置为:http:// + upstream名称,即“http://cluster”.
listen 8111;
server_name localhost;
location / {
root html;
index index.html index.htm;
proxy_pass http://cluster;
}
- 现在负载均衡初步完成了。upstream按照轮询(默认)方式进行负载,每个请求按时间顺序逐一分配到不同的后端服务器,如果后端服务器down掉,能自动剔除。虽然这种方式简便、成本低廉。但缺点是:可靠性低和负载分配不均衡。适用于图片服务器集群和纯静态页面服务器集群。
除此之外,upstream还有其它的分配策略,分别如下:
weight(权重)
upstream tomcat_cluster{
server 127.0.0.1:8850 weight=5;
server 127.0.0.1:8860 weight=10;
server 127.0.0.1:8870 weight=10;
}
服务提供者
pom
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
启动类
@EnableDiscoveryClient
配置文件
# 应用名称
spring:
application:
name: 服务名称
cloud:
nacos:
discovery:
username: nacos
password: nacos
# Nacos 服务发现与注册配置,其中子属性 server-addr 指定 Nacos 服务器主机和端口
#nacos集群 使用nginx
server-addr: localhost:8111
# 注册到 nacos 的指定 namespace,默认为 public
namespace: public
# 应用服务 WEB 访问端口
server:
port: 9010