快速導航
整合項目源碼:https://github.com/lytao123/my-alibaba-integration
項目信息:
組件 | 版本 | 描述 |
---|---|---|
Spring-Boot | 2.2.2.RELEASE | |
Spring-Cloud | Hoxton.RELEASE | |
Spring-Cloud-Alibaba | 2.2.0.RELEASE | Nacos 版本1.2.1 |
Spring-Cloud-Alibaba | 2.2.0.RELEASE | Sentinel 版本 1.7.2 |
Spring-Cloud-Alibaba | 2.2.0.RELEASE | Seata 版本 1.2.0 |
一、Nacos
1. Nacos 簡介
https://nacos.io/zh-cn/docs
Nacos 是什麼?我們來看看官網的強大介紹。
FROM https://nacos.io/zh-cn/docs/what-is-nacos.html
- Nacos 致力於幫助您發現、配置和管理微服務。Nacos 提供了一組簡單易用的特性集,幫助您快速實現動態服務發現、服務配置、服務元數據及流量管理。
- Nacos 幫助您更敏捷和容易地構建、交付和管理微服務平臺。Nacos 是構建以“服務”爲中心的現代應用架構(例如微服務範式、雲原生範式) 的服務基礎設施。
- Nacos 支持主流類型的“服務”的發現、配置和管理,包括 Spring、Spring Boot、Spring Cloud、Docker、Dubboo、Kubernates 等。特性:
- 服務發現和服務健康監測
- 動態配置服務
- 動態 DNS 服務
- 服務及其元數據管理
從上可以看出相當於加強版的 Eureka 和 配置中心結合,所以我們還是有必要學習的。
2. Nacos 安裝
- 2.1 下載 Nacos
從 https://github.com/alibaba/nacos/releases 下載對應系統版本
系統 | 系統版本 |
---|---|
Linux/Unix/Mac | .tar.gz 或 .zip |
Windows | .zip |
- 2.2 解壓
系統 | 解壓方式 |
---|---|
Linux/Unix/Mac | unzip nacos-server-$version.zip 或者 tar -xvf nacos-server-$version.tar.gz |
Windows | 使用解壓工具進行解壓 |
- 2.3 運行
系統 | 啓動方式 | 關閉方式 |
---|---|---|
Linux/Unix/Mac | 單機模式:sh startup.sh -m standalone 集羣模式: sh startup.sh |
sh shutdown.sh |
Windows | 雙擊startup.cmd運行文件或運行命令:cmd startup.cmd |
雙擊shutdown.cmd運行文件或運行命令:cmd shutdown.cmd |
-
2.4 運行成功界面
-
2.5 管理界面
訪問:http://ip:8848/nacos
用戶名密碼均爲nacos
。 -
2.6 持久化
修改nacos/conf/application.properties
文件,增加數據庫信息:
cp conf/application.properties.example conf/application.properties
vim conf/application.properties
#*************** Config Module Related Configurations ***************#
### If user MySQL as datasource:
spring.datasource.platform=mysql
### Count of DB:
db.num=1
### Connect URL of DB:
db.url.0=jdbc:mysql://192.168.136.136:3306/nacos?characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true&serverTimezone=GMT%2B8&useSSL=false
db.user=root
db.password=root
如遇到無法連接數據庫(數據庫連接信息配置正常),那這可能是數據庫驅動的問題,解決方法是在與 nacos目錄下新建文件夾 /nacos/plugins/mysql/
下載對應的 mysql 驅動jar 放置其下,然後重啓 Nacos 即可。
- 2.7 Nacos 集羣搭建
搭建 Nacos集羣比較簡單,修改/conf/cluster.conf
文件,在其增加每一個節點的 ip:port,然後分別啓動每個節點即可。以單機部署僞集羣爲例,端口 33333、44444、55555作爲集羣:
在 conf/application.properties
修改 Nacos 端口:
cp conf/application.properties.example conf/application.properties
vim conf/application.properties
cp conf/cluster.conf.example conf/cluster.conf
vim conf/cluster.conf
192.168.136.136:33333
192.168.136.136:44444
192.168.136.136:55555
分別啓動每個端口對應的 Nacos 即可,最後通過 Nginx 反向代理每個節點。參考官方集羣架構圖:
3. 整合 Spring Cloud Alibaba
- 3.1 引入 pom
<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>
- 3.2 bootstrap.yml 加入配置
nacos:
server-addr: 192.168.136.136:8848 # 單機
# server-addr: 127.0.0.1:80 # 集羣
spring:
application:
name: cloud-alibaba-order
profiles:
active: dev
cloud:
nacos:
discovery:
server-addr: ${nacos.server-addr}
config:
server-addr: ${nacos.server-addr}
file-extension: yaml
namespace: ${spring.profiles.active}
group: DEFAULT_GROUP
- 3.3 啓動應用
在主啓動類上加上註解@EnableDiscoveryClient
啓動即可。
詳細代碼請參考:https://github.com/lytao123/my-alibaba-integration
二、Sentinel
1. Sentinel 簡介
FROM https://github.com/alibaba/Sentinel/wiki/%E4%B8%BB%E9%A1%B5
Sentinel 以流量爲切入點,從流量控制、熔斷降級、系統負載保護等多個維度保護服務的穩定性。 Sentinel 具有以下特徵:
- 豐富的應用場景:Sentinel 承接了阿里巴巴近 10 年的雙十一大促流量的核心場景,例如秒殺(即突發流量控制在系統容量可以承受的範圍)、消息削峯填谷、集羣流量控制、實時熔斷下游不可用應用等。
- 完備的實時監控:Sentinel 同時提供實時的監控功能。您可以在控制檯中看到接入應用的單臺機器秒級數據,甚至 500 臺以下規模的集羣的彙總運行情況。
- 廣泛的開源生態:Sentinel 提供開箱即用的與其它開源框架/庫的整合模塊,例如與 Spring Cloud、Dubbo、gRPC 的整合。您只需要引入相應的依賴並進行簡單的配置即可快速地接入 Sentinel。
- 完善的 SPI 擴展點:Sentinel 提供簡單易用、完善的 SPI 擴展接口。您可以通過實現擴展接口來快速地定製邏輯。例如定製規則管理、適配動態數據源等。
工作流程:
2. Sentinel 安裝
-
2.1 下載
https://github.com/alibaba/Sentinel/releases
-
2.2 運行
因爲其是一個 jar 包,直接運行即可,運行命令可以參考下面的,其他命令也可以。
nohup java -jar sentinel-dashboard-1.7.2.jar &
- 2.3 管理界面
訪問地址:http://ip:8080
,用戶名密碼均爲sentinel
.
- 2.4 持久化 Sentinel 配置到 Nacos
規則:在對應 namespace和group下創建 application-name
[
{
"resource" : "cluster-resource", // 限流的資源名稱
"grade" : 1, // 限流模式爲:qps
"count" : 10, // 閾值爲:10
"clusterMode" : true, // 集羣模式爲:true
"clusterConfig" : {
"flowId" : 111, // 全局唯一id
"thresholdType" : 1, // 閾值模式僞:全局閾值
"fallbackToLocalWhenFail" : true // 在 client 連接失敗或通信失敗時,是否退化到本地的限流模式
}
}
]
3. 整合 Spring Cloud Alibaba
- 3.1 引入 pom
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
<!-- sentinel 持久化包 -->
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-datasource-nacos</artifactId>
</dependency>
- 3.2 bootstrap.yml 加入配置
nacos:
server-addr: 192.168.136.136:8848 # 單機
# server-addr: 127.0.0.1:80 # 集羣
spring:
application:
name: cloud-alibaba-order
profiles:
active: dev
cloud:
nacos:
discovery:
server-addr: ${nacos.server-addr}
config:
server-addr: ${nacos.server-addr}
file-extension: yaml
namespace: ${spring.profiles.active}
group: DEFAULT_GROUP
sentinel:
# 針對 alibaba 2.2 版本兼容 start
eager: true
filter:
url-patterns: /**
# 針對 alibaba 2.2 版本兼容 end
transport:
dashboard: http://192.168.136.136:8080
port: 8719 # 默認8719,假如被佔用了會自動從8719開始依次+1掃描。直至找到未被佔用的端口
# 持久化 sentinel
datasource:
ds1:
nacos:
server-addr: ${nacos.server-addr}
dataId: ${spring.application.name}
groupId: ${spring.cloud.nacos.config.group}
namespace: ${spring.cloud.nacos.config.namespace}
data-type: json
rule-type: flow
- 3.3 啓動應用
啓動應用即可。各種限流+熔斷+降級+監控等通過@SentinelResource
+ 控制檯配置。
詳細請參考:https://github.com/lytao123/my-alibaba-integration
三、Seata
1. Seata 簡介
Seata 是一款開源的分佈式事務解決方案,致力於提供高性能和簡單易用的分佈式事務服務。Seata 將爲用戶提供了 AT、TCC、SAGA 和 XA 事務模式,爲用戶打造一站式的分佈式解決方案。
2. Seata 安裝
-
2.1 下載
下載鏈接:https://github.com/seata/seata/releases, 目前最新版爲 1.2.0 -
2.2 解壓
tar -zxvf seata-server-1.2.0.tar.gz
unzip seata-server-1.2.0.tar.gz
- 2.3 啓動
單機版可以直接運行命令sh bin/seata-server.sh
即可,默認端口是8091
,啓動成功日誌打印:
2020-06-13 19:34:21.683 WARN [main]i.s.c.l.EnhancedServiceLoader$InnerEnhancedServiceLoader.loadFile:482 -The same extension io.seata.server.storage.db.lock.DataBaseLockManager has already been loaded, skipped
2020-06-13 19:34:21.684 WARN [main]i.s.c.l.EnhancedServiceLoader$InnerEnhancedServiceLoader.loadFile:482 -The same extension io.seata.server.storage.file.lock.FileLockManager has already been loaded, skipped
2020-06-13 19:34:21.829 INFO [main]io.seata.core.rpc.netty.RpcServerBootstrap.start:155 -Server started ...
這裏我們已集羣爲例。
首先切到目前 /seata/conf/
下 cd seata/conf/
修改 registry.conf 內容,配置 type = "nacos"
及 nacos 信息
# 其他組件的我已經刪掉了
registry {
# file 、nacos 、eureka、redis、zk、consul、etcd3、sofa
type = "nacos" # 改爲 nacos
nacos {
application = "seata-server"
serverAddr = "127.0.0.1"
cluster = "default"
namespace = ""
}
}
config {
# file、nacos 、apollo、zk、consul、etcd3
type = "nacos" # 改爲 nacos
nacos {
serverAddr = "127.0.0.1"
namespace = ""
}
}
修改 file.conf 內容,配置 mode = "db"
並配置數據庫信息
## transaction log store, only used in seata-server
store {
## store mode: file、db
mode = "db" # 設置db模式
## database store property
db {
## the implement of javax.sql.DataSource, such as DruidDataSource(druid)/BasicDataSource(dbcp) etc.
datasource = "druid"
## mysql/oracle/postgresql/h2/oceanbase etc.
dbType = "mysql"
#driverClassName = "com.mysql.jdbc.Driver"
driverClassName = "com.mysql.cj.jdbc.Driver" # MYSQL 8 JDBC 驅動
url = "jdbc:mysql://192.168.136.136:3306/seata"
user = "root"
password = "root"
minConn = 5
maxConn = 30
globalTable = "global_table"
branchTable = "branch_table"
lockTable = "lock_table"
queryLimit = 100
maxWait = 5000
}
}
如果是 Mysql 8 不僅要修改JDBC 驅動,還需將其驅動包放到 lib
目錄下。
在剛纔配置的數據庫下執行建表語句:
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for branch_table
-- ----------------------------
DROP TABLE IF EXISTS `branch_table`;
CREATE TABLE `branch_table` (
`branch_id` bigint(0) NOT NULL,
`xid` varchar(128) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
`transaction_id` bigint(0) NULL DEFAULT NULL,
`resource_group_id` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`resource_id` varchar(256) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`branch_type` varchar(8) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`status` tinyint(0) NULL DEFAULT NULL,
`client_id` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`application_data` varchar(2000) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`gmt_create` datetime(6) NULL DEFAULT NULL,
`gmt_modified` datetime(6) NULL DEFAULT NULL,
PRIMARY KEY (`branch_id`) USING BTREE,
INDEX `idx_xid`(`xid`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of branch_table
-- ----------------------------
-- ----------------------------
-- Table structure for global_table
-- ----------------------------
DROP TABLE IF EXISTS `global_table`;
CREATE TABLE `global_table` (
`xid` varchar(128) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
`transaction_id` bigint(0) NULL DEFAULT NULL,
`status` tinyint(0) NOT NULL,
`application_id` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`transaction_service_group` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`transaction_name` varchar(128) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`timeout` int(0) NULL DEFAULT NULL,
`begin_time` bigint(0) NULL DEFAULT NULL,
`application_data` varchar(2000) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`gmt_create` datetime(0) NULL DEFAULT NULL,
`gmt_modified` datetime(0) NULL DEFAULT NULL,
PRIMARY KEY (`xid`) USING BTREE,
INDEX `idx_gmt_modified_status`(`gmt_modified`, `status`) USING BTREE,
INDEX `idx_transaction_id`(`transaction_id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of global_table
-- ----------------------------
-- ----------------------------
-- Table structure for lock_table
-- ----------------------------
DROP TABLE IF EXISTS `lock_table`;
CREATE TABLE `lock_table` (
`row_key` varchar(128) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
`xid` varchar(96) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`transaction_id` bigint(0) NULL DEFAULT NULL,
`branch_id` bigint(0) NOT NULL,
`resource_id` varchar(256) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`table_name` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`pk` varchar(36) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`gmt_create` datetime(0) NULL DEFAULT NULL,
`gmt_modified` datetime(0) NULL DEFAULT NULL,
PRIMARY KEY (`row_key`) USING BTREE,
INDEX `idx_branch_id`(`branch_id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
SET FOREIGN_KEY_CHECKS = 1;
另外每個業務數據庫也需要創建 undo_log
表
DROP TABLE IF EXISTS `undo_log`;
CREATE TABLE `undo_log` (
`id` bigint(0) NOT NULL AUTO_INCREMENT,
`branch_id` bigint(0) NOT NULL,
`xid` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
`context` varchar(128) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
`rollback_info` longblob NOT NULL,
`log_status` int(0) NOT NULL,
`log_created` datetime(0) NOT NULL,
`log_modified` datetime(0) NOT NULL,
PRIMARY KEY (`id`) USING BTREE,
UNIQUE INDEX `ux_undo_log`(`xid`, `branch_id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
SET FOREIGN_KEY_CHECKS = 1;
此外,爲方便 application 連接使用,
新建 config.txt ,編輯內容爲:
service.vgroupMapping.test_tx_group=default # test_tx_group 自己設置,application 中 tx-service-group 與其一致
store.mode=db
store.db.datasource=druid
store.db.dbType=mysql
store.db.driverClassName=com.mysql.cj.jdbc.Driver
store.db.url=jdbc:mysql://192.168.136.136:3306/seata?useUnicode=true
store.db.user=root
store.db.password=root
store.db.minConn=5
store.db.maxConn=30
store.db.globalTable=global_table
store.db.branchTable=branch_table
store.db.lockTable=lock_table
store.db.queryLimit=100
store.db.maxWait=5000
通過 nacos-config.sh
工具 將 config.txt 中信息導入 Nacos 中
下面爲工具代碼,複製保存成 .sh 文件
: 工具下載地址
#!/usr/bin/env bash
# Copyright 1999-2019 Seata.io Group.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at、
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
while getopts ":h:p:g:t:u:w:" opt
do
case $opt in
h)
host=$OPTARG
;;
p)
port=$OPTARG
;;
g)
group=$OPTARG
;;
t)
tenant=$OPTARG
;;
u)
username=$OPTARG
;;
w)
password=$OPTARG
;;
?)
echo " USAGE OPTION: $0 [-h host] [-p port] [-g group] [-t tenant] [-u username] [-w password] "
exit 1
;;
esac
done
if [[ -z ${host} ]]; then
host=localhost
fi
if [[ -z ${port} ]]; then
port=8848
fi
if [[ -z ${group} ]]; then
group="SEATA_GROUP"
fi
if [[ -z ${tenant} ]]; then
tenant=""
fi
if [[ -z ${username} ]]; then
username=""
fi
if [[ -z ${password} ]]; then
password=""
fi
nacosAddr=$host:$port
contentType="content-type:application/json;charset=UTF-8"
echo "set nacosAddr=$nacosAddr"
echo "set group=$group"
failCount=0
tempLog=$(mktemp -u)
function addConfig() {
curl -X POST -H "${contentType}" "http://$nacosAddr/nacos/v1/cs/configs?dataId=$1&group=$group&content=$2&tenant=$tenant&username=$username&password=$password" >"${tempLog}" 2>/dev/null
if [[ -z $(cat "${tempLog}") ]]; then
echo " Please check the cluster status. "
exit 1
fi
if [[ $(cat "${tempLog}") =~ "true" ]]; then
echo "Set $1=$2 successfully "
else
echo "Set $1=$2 failure "
(( failCount++ ))
fi
}
count=0
for line in $(cat $(dirname "$PWD")/conf/config.txt | sed s/[[:space:]]//g); do
(( count++ ))
key=${line%%=*}
value=${line#*=}
addConfig "${key}" "${value}"
done
echo "========================================================================="
echo " Complete initialization parameters, total-count:$count , failure-count:$failCount "
echo "========================================================================="
if [[ ${failCount} -eq 0 ]]; then
echo " Init nacos config finished, please start seata-server. "
else
echo " init nacos config fail. "
fi
最後啓動:
# 啓動第一個節點
nohup sh bin/seata-server.sh -h 192.168.136.136 -p 18091 -n 1 &
# 啓動第二個節點
nohup sh bin/seata-server.sh -h 192.168.136.136 -p 28091 -n 2 &
# -h : nacos ip
# -p : 端口
# -n: transactionId 事務編號,在多個 TC Server 時,區分各自節點
3. 整合 Spring Cloud Alibaba
3.1 pom
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-seata</artifactId>
</dependency>
<dependency>
<groupId>io.seata</groupId>
<artifactId>seata-spring-boot-starter</artifactId>
<version>1.2.0</version>
</dependency>
3.2 bootstrap.yml 加入配置
# seata 配置項,對應 SeataProperties 類
seata:
application-id: ${spring.application.name} # seata 應用編號,默認爲 ${spring.application.name}
tx-service-group: test_tx_group # seata 事務組編號,用於 TC 集羣名
# seata 服務配置項,對應 ServiceProperties 類
service:
grouplist:
seata-server: 192.168.136.136:8091
# 虛擬組和分組的映射, key一定要與 tx-service-group一致
vgroupMapping:
test_tx_group: default
# seata 註冊中心配置項,對應 RegistryProperties 類
registry:
type: nacos # 註冊中心類型,默認爲 file
nacos:
server-addr: ${nacos.server-addr} # Nacos 服務地址
config:
type: nacos # 註冊中心類型,默認爲 file
nacos:
server-addr: ${nacos.server-addr} # Nacos 服務地址
3.3 在需要分佈式事務的 Service 方法上增加註解 @GlobalTransactional
3.4 啓動測試
詳細代碼請參考:https://github.com/lytao123/my-alibaba-integration