附:
1.预备环境准备
注:如果没有安装64位的jdk1.8或者以上版本,在启动nacos,会报错。
[root@localhost bin]# sh startup.sh -m standalone
which: no javac in (/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin)
readlink: 缺少操作数
Try 'readlink --help' for more information.
dirname: 缺少操作数
Try 'dirname --help' for more information.
ERROR: Please set the JAVA_HOME variable in your environment, We need java(x64)! jdk8 or later is better! !!
1.1 解压jdk、nacos、seata:
[root@localhost software]# tar -zxvf jdk-8u241-linux-x64.tar.gz && tar -zxvf nacos-server-1.3.0.tar.gz && tar -zxvf seata-server-1.2.0.tar.gz
jdk1.8.0_241/
1.2 配置jdk环境
附:安装配置jdk
2. nacos
[root@localhost software]# cd nacos
[root@localhost nacos]# cd bin
[root@localhost bin]# sh startup.sh -m standalone
/software/jdk1.8.0_241/bin/java -Xms512m -Xmx512m -Xmn256m -Dnacos.standalone=true -Dnacos.member.list= -Djava.ext.dirs=/software/jdk1.8.0_241/jre/lib/ext:/software/jdk1.8.0_241/lib/ext -Xloggc:/software/nacos/logs/nacos_gc.log -verbose:gc -XX:+PrintGCDetails -XX:+PrintGCDateStamps -XX:+PrintGCTimeStamps -XX:+UseGCLogFileRotation -XX:NumberOfGCLogFiles=10 -XX:GCLogFileSize=100M -Dloader.path=/software/nacos/plugins/health,/software/nacos/plugins/cmdb,/software/nacos/plugins/mysql -Dnacos.home=/software/nacos -jar /software/nacos/target/nacos-server.jar --spring.config.location=classpath:/,classpath:/config/,file:./,file:./config/,file:/software/nacos/conf/ --logging.config=/software/nacos/conf/nacos-logback.xml --server.max-http-header-size=524288
nacos is starting with standalone
nacos is starting,you can check the /software/nacos/logs/start.out
附:
1.Linux/Unix/Mac
启动命令(standalone代表着单机模式运行,非集群模式):
sh startup.sh -m standalone
2.如果您使用的是ubuntu系统,或者运行脚本报错提示[[符号找不到,可尝试如下运行:
bash startup.sh -m standalone
3.Windows
启动命令:
cmd startup.cmd
或者双击startup.cmd运行文件。
查看nacos启动日志:
[root@localhost bin]# cat /software/nacos/logs/start.out
日志内容:
日志内容最后一行: 代表启动成功了。
2020-06-18 11:06:01,926 INFO Nacos started successfully in stand alone mode. use embedded storage
访问浏览器http://192.168.24.140:8848/nacos/index.html,使用账号/密码:nacos/nacos登录。
注:使用宿主机去远程访问虚拟机,需要开放端口,或者关闭虚拟机防火墙:
[root@localhost bin]# systemctl stop firewalld.service
[root@localhost bin]# systemctl disable firewalld.service
Removed symlink /etc/systemd/system/multi-user.target.wants/firewalld.service.
Removed symlink /etc/systemd/system/dbus-org.fedoraproject.FirewallD1.service.
3. seata
3.1 file.conf:(这里其实不用配,我这里用不到)
3.2 registy.conf:
registry {
# file 、nacos 、eureka、redis、zk、consul、etcd3、sofa
type = "nacos"
nacos {
application = "seata-server"
serverAddr = "localhost"
namespace = ""
cluster = "default"
username = ""
password = ""
}
}
config {
# file、nacos 、apollo、zk、consul、etcd3
type = "nacos"
nacos {
serverAddr = "localhost"
namespace = ""
group = "SEATA_GROUP"
username = ""
password = ""
}
}
3.3 创建seata数据库,并创建三张表:
-- -------------------------------- The script used when storeMode is 'db' --------------------------------
-- the table to store GlobalSession data
CREATE TABLE IF NOT EXISTS `global_table`
(
`xid` VARCHAR(128) NOT NULL,
`transaction_id` BIGINT,
`status` TINYINT NOT NULL,
`application_id` VARCHAR(32),
`transaction_service_group` VARCHAR(32),
`transaction_name` VARCHAR(128),
`timeout` INT,
`begin_time` BIGINT,
`application_data` VARCHAR(2000),
`gmt_create` DATETIME,
`gmt_modified` DATETIME,
PRIMARY KEY (`xid`),
KEY `idx_gmt_modified_status` (`gmt_modified`, `status`),
KEY `idx_transaction_id` (`transaction_id`)
) ENGINE = InnoDB
DEFAULT CHARSET = utf8;
-- the table to store BranchSession data
CREATE TABLE IF NOT EXISTS `branch_table`
(
`branch_id` BIGINT NOT NULL,
`xid` VARCHAR(128) NOT NULL,
`transaction_id` BIGINT,
`resource_group_id` VARCHAR(32),
`resource_id` VARCHAR(256),
`branch_type` VARCHAR(8),
`status` TINYINT,
`client_id` VARCHAR(64),
`application_data` VARCHAR(2000),
`gmt_create` DATETIME(6),
`gmt_modified` DATETIME(6),
PRIMARY KEY (`branch_id`),
KEY `idx_xid` (`xid`)
) ENGINE = InnoDB
DEFAULT CHARSET = utf8;
-- the table to store lock data
CREATE TABLE IF NOT EXISTS `lock_table`
(
`row_key` VARCHAR(128) NOT NULL,
`xid` VARCHAR(96),
`transaction_id` BIGINT,
`branch_id` BIGINT NOT NULL,
`resource_id` VARCHAR(256),
`table_name` VARCHAR(32),
`pk` VARCHAR(36),
`gmt_create` DATETIME,
`gmt_modified` DATETIME,
PRIMARY KEY (`row_key`),
KEY `idx_branch_id` (`branch_id`)
) ENGINE = InnoDB
DEFAULT CHARSET = utf8;
3.3 将seata配置推送到nacos
在1.2版本已经不在给我们的包中提供这些文件了 :(1)nacos-config.sh (2)config.txt
可以在seata的GitHub项目中找到对应的文件:https://github.com/seata/seata/tree/1.2.0/script/config-center
config.txt:(根据自己需要修改,跟file.conf内容其实一样)
transport.type=TCP
transport.server=NIO
transport.heartbeat=true
transport.enableClientBatchSendRequest=false
transport.threadFactory.bossThreadPrefix=NettyBoss
transport.threadFactory.workerThreadPrefix=NettyServerNIOWorker
transport.threadFactory.serverExecutorThreadPrefix=NettyServerBizHandler
transport.threadFactory.shareBossWorker=false
transport.threadFactory.clientSelectorThreadPrefix=NettyClientSelector
transport.threadFactory.clientSelectorThreadSize=1
transport.threadFactory.clientWorkerThreadPrefix=NettyClientWorkerThread
transport.threadFactory.bossThreadSize=1
transport.threadFactory.workerThreadSize=default
transport.shutdown.wait=3
service.vgroupMapping.storage-service-group=default
service.vgroupMapping.order-service-group=default
service.default.grouplist=127.0.0.1:8091
service.enableDegrade=false
service.disableGlobalTransaction=false
client.rm.asyncCommitBufferLimit=10000
client.rm.lock.retryInterval=10
client.rm.lock.retryTimes=30
client.rm.lock.retryPolicyBranchRollbackOnConflict=true
client.rm.reportRetryCount=5
client.rm.tableMetaCheckEnable=false
client.rm.sqlParserType=druid
client.rm.reportSuccessEnable=false
client.rm.sagaBranchRegisterEnable=false
client.tm.commitRetryCount=5
client.tm.rollbackRetryCount=5
store.mode=db
store.file.dir=file_store/data
store.file.maxBranchSessionSize=16384
store.file.maxGlobalSessionSize=512
store.file.fileWriteBufferCacheSize=16384
store.file.flushDiskMode=async
store.file.sessionReloadReadSize=100
store.db.datasource=druid
store.db.dbType=mysql
store.db.driverClassName=com.mysql.cj.jdbc.Driver
store.db.url=jdbc:mysql://127.0.0.1:3306/seata?useUnicode=true
store.db.user=root
store.db.password=123456
store.db.minConn=5
store.db.maxConn=30
store.db.globalTable=global_table
store.db.branchTable=branch_table
store.db.queryLimit=100
store.db.lockTable=lock_table
store.db.maxWait=5000
server.recovery.committingRetryPeriod=1000
server.recovery.asynCommittingRetryPeriod=1000
server.recovery.rollbackingRetryPeriod=1000
server.recovery.timeoutRetryPeriod=1000
server.maxCommitRetryTimeout=-1
server.maxRollbackRetryTimeout=-1
server.rollbackRetryTimeoutUnlockEnable=false
client.undo.dataValidation=true
client.undo.logSerialization=jackson
server.undo.logSaveDays=7
server.undo.logDeletePeriod=86400000
client.undo.logTable=undo_log
client.log.exceptionRate=100
transport.serialization=seata
transport.compressor=none
metrics.enabled=false
metrics.registryType=compact
metrics.exporterList=prometheus
metrics.exporterPrometheusPort=9898
ps:这里因为是mysql8.0.因此这里用的是com.mysql.cj.jdbc.Driver,否则在启动seata时,会报空指针,获取连接失败。
nacos-config.sh:(直接从GitHub上seata项目中拷贝即可)
#!/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:" opt
do
case $opt in
h)
host=$OPTARG
;;
p)
port=$OPTARG
;;
g)
group=$OPTARG
;;
t)
tenant=$OPTARG
;;
?)
echo " USAGE OPTION: $0 [-h host] [-p port] [-g group] [-t tenant] "
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
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 "${1}" "http://$2/nacos/v1/cs/configs?dataId=$3&group=$group&content=$4&tenant=$tenant" >"${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 $3=$4 successfully "
else
echo "Set $3=$4 failure "
(( failCount++ ))
fi
}
count=0
for line in $(cat $(dirname "$PWD")/config.txt | sed s/[[:space:]]//g); do
(( count++ ))
key=${line%%=*}
value=${line#*=}
addConfig "${contentType}" "${nacosAddr}" "${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
注:store.db.driverClassName这个配置如果是mysql8.0,这里需要改成com.mysql.cj.jdbc.Driver,刚开始我使用默认的com.mysql.jdbc.Driver,导致seata无法启动,连接不上。
使用脚本,将seata的配置推送到nacos中:
[root@localhost conf]# sh nacos-config.sh localhost
注:如果这一步推送服务出错,而你确实是从seata的GitHub中拷贝下来的,确保没有问题,却提示语法错误,首先看下文件是否是utf-8。
参数说明:
-h: host,默认值 localhost
-p: port,默认值 8848
-g: 配置分组,默认值为 'SEATA_GROUP'
-t: 租户信息,对应 Nacos 的命名空间ID字段, 默认值为空 ''
执行脚本后,控制台打印:
=========================================================================
Complete initialization parameters, total-count:68 , failure-count:0
=========================================================================
Init nacos config finished, please start seata-server.
再次访问浏览器http://192.168.24.140:8848/nacos/index.html,使用账号/密码:nacos/nacos登录
会看到大量的配置加载到了nacos当中,这里我根据Data Id为service.vgroupMapping.${your-service-gruop},,可以看到storage-service-group和order-service-group配置也被加载到了nacos中。
ps: 当然也可以使用如下命令将seata的配置推送到nacos:(这里选其中一种即可,我就直接使用上面那种,用默认的命名空间public了)
创建命名空间:
[root@localhost conf]# sh nacos-config.sh -h localhost -p 8848 -g SEATA_GROUP -t eadf9fc7-4f4b-4134-81a0-e82e06268965
访问浏览器http://192.168.24.140:8848/nacos/index.html,使用账号/密码:nacos/nacos登录
3.4 启动seata
[root@localhost seata]# cd bin
[root@localhost bin]# sh seata-server.sh -p 8091 -h 192.168.24.140 -m db
#下面两种启动命令参考:
cd bin
sh seata-server.sh -p 8091 -m db
#or
sh seata-server.sh
控制台:
注:如果seata服务端的registy.conf文件没有配置,启动seata会提示无法创建mysql连接,并一直空指针异常,假如你想使用nacos做为配置中心,里面存放seata的配置,那么就是从nacos中读取你的配置,你不配置registy.conf,seata就读不到。
再次访问nacos:查看服务列表seata-server被注册进去了
点击详情查看:
注:seata 1.2的服务名是seata-server,1.2版本以前不是叫这个名字,另外这个ip地址查看是否是虚拟机ip,我原先启动seata直接使用sh seata-server.sh,
并没有指定ip,启动项目后:
问题:
报
io.seata.common.exception.FrameworkException: can not register RM,err:can not connect to services-server.
解决:
参考:(1)https://github.com/seata/seata/issues/2522 (2)https://seata.io/zh-cn/docs/overview/faq.html
使用jps查看: 除了jps本身之外,server是seata的,nacos-server.jar是nacos:
[root@localhost ~]# jps
16803 Server
16220 nacos-server.jar
16879 Jps
4. 代码
4.1 order-service
<!-- seata-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-seata</artifactId>
<version>2.1.1.RELEASE</version>
<exclusions>
<exclusion>
<groupId>io.seata</groupId>
<artifactId>seata-all</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>io.seata</groupId>
<artifactId>seata-all</artifactId>
<version>1.2.0</version>
</dependency>
application.yml: (registry.conf中内容挪到了application.yml中,因此不需要registry.conf文件,只要一个application.yml即可)
server:
port: 8080
spring:
application:
name: order-service
datasource:
druid:
url: jdbc:mysql://192.168.24.140:3306/seata_order?allowMultiQueries=true&useSSL=false
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
cloud:
nacos: # Nacos 注册中心地址
discovery:
server-addr: 192.168.24.140:8848
seata:
enabled: true
application-id: ${spring.application.name}
tx-service-group: ${spring.application.name}-group
enable-auto-data-source-proxy: true
config:
type: nacos
nacos:
namespace:
serverAddr: 192.168.24.140:8848
group: SEATA_GROUP
userName: "nacos"
password: "nacos"
registry:
type: nacos
nacos:
application: seata-server
server-addr: 192.168.24.140:8848
namespace:
userName: "nacos"
password: "nacos"
logging:
level:
io.seata: debug
4.2 storage-service
ps:
pom.xml中引入seata包一致,application.yml中大部分一致,数据库名改成storage-service自己的库,应用名改成storage-service即可。
4.3 测试
启动成功:控制台也并无报错:
postman测试:
(1)成功提交:localhost:8080/order/placeOrder/commit
数据库中:订单表已经有一条数据,库存表商品库存数量减1
(2)失败回滚:localhost:8080/order/placeOrder/rollback
order-service服务远程调用storage-service服务:
在storage-service服务中,模拟异常:
order-service: 控制台打印信息
2020-07-01 14:22:51.129 INFO 23884 --- [nio-8080-exec-3] i.seata.tm.api.DefaultGlobalTransaction : [192.168.24.140:8091:2015773465] rollback status: Rollbacked
2020-07-01 14:22:51.145 ERROR 23884 --- [nio-8080-exec-3] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is feign.FeignException: status 500 reading StorageFeignClient#deduct(String,Integer); content:
{"timestamp":"2020-07-01T06:22:51.001+0000","status":500,"error":"Internal Server Error","message":"异常:模拟业务异常:Storage branch exception","path":"/storage/deduct"}] with root cause
feign.FeignException: status 500 reading StorageFeignClient#deduct(String,Integer); content:
{"timestamp":"2020-07-01T06:22:51.001+0000","status":500,"error":"Internal Server Error","message":"异常:模拟业务异常:Storage branch exception","path":"/storage/deduct"}
at feign.FeignException.errorStatus(FeignException.java:62) ~[feign-core-9.5.1.jar:na]
storage-service:控制台打印信息
2020-07-01 14:22:50.986 WARN 15036 --- [nio-9080-exec-3] c.a.c.seata.web.SeataHandlerInterceptor : xid in change during RPC from 192.168.24.140:8091:2015773465 to null
2020-07-01 14:22:50.994 ERROR 15036 --- [nio-9080-exec-3] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.RuntimeException: 异常:模拟业务异常:Storage branch exception] with root cause
java.lang.RuntimeException: 异常:模拟业务异常:Storage branch exception
at com.work.storage.service.StorageService.deduct(StorageService.java:37) ~[classes/:na]
at com.work.storage.service.StorageService$$FastClassBySpringCGLIB$$1fc49d96.invoke(<generated>) ~[classes/:na]
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) ~[spring-core-5.0.10.RELEASE.jar:5.0.10.RELEASE]
ps:
在启动order-service和storage-service服务后,用postman测试接口提示如下问题:
Could not commit JDBC transaction; nested exception is io.seata.rm.datasource.exec.LockConflictException: get global lock fail
我发现seata表中有数据,于是我将seata表中的数据都删了,重启seata,然后再启动项目,问题没有再出现了。
注:
当我删掉service.vgroupMapping.storage-service-group和service.vgroupMapping.order-service-group这两个配置。
控制台立马报错:i.s.c.r.netty.NettyClientChannelManager : no available service 'null' found, please make sure registry config correct
因此这个错误可能是:
(1)是不是将seata的配置推送到了nacos当中(上面有推送的方法)。
(2)首先检查客户端代码配置的seata.tx-service-group: ${spring.application.name}-group与nacos中的配置service.vgroupMapping.${spring.application.name}-group的${spring.application.name}是不是一致。