1.官网下载seata(1.5.2)
1.1.配置seata application.yml
1.2. 配置seata在 nacos 配置信息
1.3.java服务在nacos中配置seata信息
2.配置数据库表(undo_log)信息
3.配置java pom.xml信息
4.书写java代码
1.官网下载seata(1.5.2)
1.1.打开E:\java\xxxxx\seata-server1.5.2\seata\confseata\application.yml
name:服务名称
type:注册方式
tx-service-group:分组
default_tx_group:默认分组
namespace:nacos命名空间
group:nacos分组类型
dataId:指向nacos配置文件
---------------------------------------------------------------------------------------------------------------------------------
下图配置文件可以直接复制到(seata1.5.2\seata\conf\application.yml)
server:
port: 7091
spring:
application:
name: seata-server
logging:
config: classpath:logback-spring.xml
file:
path: ${user.home}/logs/seata
extend:
logstash-appender:
destination: 127.0.0.1:4560
kafka-appender:
bootstrap-servers: 127.0.0.1:9092
topic: logback_to_logstash
console:
user:
username: seata
password: seata
seata:
enabled: true
tx-service-group: default_tx_group
application-id: ${spring.application.name}
enable-auto-data-source-proxy: true
#数据源代理模式使用AT模式(可以不用配置,seata默认使用AT模式)
data-source-proxy-mode: AT
#事务群组(可以每个应用独立取名,也可以使用相同的名字),要与服务端seataServer.properties中service.vgroup_mapping中存在,并且要保证多个群组情况下后缀名要保持一致-tx_group
# support: nacos, consul, apollo, zk, etcd3
service:
vgroup-mapping:
default_tx_group: default
type: nacos
nacos:
server-addr: 127.0.0.1:8848
namespace: "text-local"
group: "DEFAULT_GROUP"
dataId: "seataServer.properties"
username: "nacos"
password: "nacos"
registry:
# support: nacos, eureka, redis, zk, consul, etcd3, sofa
type: nacos
nacos:
application: seata-server
server-addr: 127.0.0.1:8848
group: "DEFAULT_GROUP"
namespace: "text-local"
username: "nacos"
password: "nacos"
# store:
# support: file 、 db 、 redis
# mode: file
# server:
# service-port: 8091 #If not configured, the default is '${server.port} + 1000'
security:
secretKey: SeataSecretKey0c382ef121d778043159209298fd40bf3850a017
tokenValidityInMilliseconds: 1800000
ignore:
urls: /,/**/*.css,/**/*.js,/**/*.html,/**/*.map,/**/*.svg,/**/*.png,/**/*.ico,/console-fe/public/**,/api/v1/auth/login
1.2. 配置seata在 nacos 配置信息
1).在nacos中配置seata命名空间
2).在nacos中配置seata配置seataServer.properties
3.下图配置来介绍seataServer.properties在nacos配置信息中的内容
1).seata分
2).配置seata连接数据库
3).Nacos seataServer.properties 配置信息(可以直接拷贝复用)
#For details about configuration items, see https://seata.io/zh-cn/docs/user/configurations.html
#Transport configuration, for client and server
transport.type=TCP
transport.server=NIO
transport.heartbeat=true
transport.enableTmClientBatchSendRequest=false
transport.enableRmClientBatchSendRequest=true
transport.enableTcServerBatchSendResponse=false
transport.rpcRmRequestTimeout=30000
transport.rpcTmRequestTimeout=30000
transport.rpcTcRequestTimeout=30000
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
transport.serialization=seata
transport.compressor=none
#Transaction routing rules configuration, only for the client
# default_tx_group 这个要注意 后面要和java代码写的一致
service.vgroupMapping.default_tx_group=default_tx_group
#If you use a registry, you can ignore it
service.default_tx_group.grouplist=127.0.0.1:8091
service.enableDegrade=false
service.disableGlobalTransaction=false
#Transaction rule configuration, only for the client
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=true
client.rm.tableMetaCheckerInterval=60000
client.rm.sqlParserType=druid
client.rm.reportSuccessEnable=false
client.rm.sagaBranchRegisterEnable=false
client.rm.sagaJsonParser=fastjson
client.rm.tccActionInterceptorOrder=-2147482648
client.tm.commitRetryCount=5
client.tm.rollbackRetryCount=5
client.tm.defaultGlobalTransactionTimeout=60000
client.tm.degradeCheck=false
client.tm.degradeCheckAllowTimes=10
client.tm.degradeCheckPeriod=2000
client.tm.interceptorOrder=-2147482648
client.undo.dataValidation=true
client.undo.logSerialization=jackson
client.undo.onlyCareUpdateColumns=true
server.undo.logSaveDays=7
server.undo.logDeletePeriod=86400000
client.undo.logTable=undo_log
client.undo.compress.enable=true
client.undo.compress.type=zip
client.undo.compress.threshold=64k
#For TCC transaction mode
tcc.fence.logTableName=tcc_fence_log
tcc.fence.cleanPeriod=1h
#Log rule configuration, for client and server
log.exceptionRate=100
#Transaction storage configuration, only for the server. The file, DB, and redis configuration values are optional.
store.mode=file
store.lock.mode=file
store.session.mode=file
#Used for password encryption
store.publicKey=
#If `store.mode,store.lock.mode,store.session.mode` are not equal to `file`, you can remove the configuration block.
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
#These configurations are required if the `store mode` is `db`. If `store.mode,store.lock.mode,store.session.mode` are not equal to `db`, you can remove the configuration block.
#修改这里的数据库配置就行
store.db.datasource=druid
store.db.dbType=mysql
store.db.driverClassName=com.mysql.jdbc.Driver
store.db.url=mysql://localhost:3306/seata?allowMultiQueries=true&rewriteBatchedStatements=true&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=Asia/Shanghai
store.db.user=username
store.db.password=username
store.db.minConn=5
store.db.maxConn=30
store.db.globalTable=global_table
store.db.branchTable=branch_table
store.db.distributedLockTable=distributed_lock
store.db.queryLimit=100
store.db.lockTable=lock_table
store.db.maxWait=5000
#These configurations are required if the `store mode` is `redis`. If `store.mode,store.lock.mode,store.session.mode` are not equal to `redis`, you can remove the configuration block.
store.redis.mode=single
store.redis.single.host=127.0.0.1
store.redis.single.port=6379
store.redis.sentinel.masterName=
store.redis.sentinel.sentinelHosts=
store.redis.maxConn=10
store.redis.minConn=1
store.redis.maxTotal=100
store.redis.database=0
store.redis.password=
store.redis.queryLimit=100
#Transaction rule configuration, only for the server
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
server.distributedLockExpireTime=10000
server.xaerNotaRetryTimeout=60000
server.session.branchAsyncQueueSize=5000
server.session.enableBranchAsyncRemove=false
server.enableParallelRequestHandle=false
#Metrics configuration, only for the server
metrics.enabled=false
metrics.registryType=compact
metrics.exporterList=prometheus
metrics.exporterPrometheusPort=9898
1.3.在nacos中配置 java注册的seata信息
1).备注:下图seata配置信息需要配置到nacos集成的java配置文件中(如果a,b服务需要跨服务调用分别拷贝到各自的配置文件服务下)
seata:
enabled: true
application-id: ${spring.application.name}
tx-service-group: default_tx_group
service:
vgroup-mapping:
default_tx_group: default_tx_group
grouplist:
default_tx_group: 127.0.0.1:8091 #这里是seata的ip 端口
config:
type: nacos
nacos:
server-addr: 127.0.0.1:8848
group: DEFAULT_GROUP
namespace: spdb-local
username: nacos
password: nacos
data-id: seataServer.properties
2.配置数据库表(undo_log)信息
undo_log表用来记录分布式事务数据镜像,事务失败用来回滚对应信息,事务成功删除对应信息
-- dlndata.undo_log definition
CREATE TABLE `undo_log` (
`branch_id` bigint NOT NULL COMMENT 'branch transaction id',
`xid` varchar(100) NOT NULL COMMENT 'global transaction id',
`context` varchar(128) NOT NULL COMMENT 'undo_log context,such as serialization',
`rollback_info` longblob NOT NULL COMMENT 'rollback info',
`log_status` int NOT NULL COMMENT '0:normal status,1:defense status',
`log_created` datetime(6) NOT NULL COMMENT 'create datetime',
`log_modified` datetime(6) NOT NULL COMMENT 'modify datetime',
UNIQUE KEY `ux_undo_log` (`xid`,`branch_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COMMENT='AT transaction mode undo table';
3.配置SpringCloud pom.xml
如果SpringCloud中没有@GlobalTransactional分布式事务注解
请在pom.xml中添加seata pom
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-seata</artifactId>
<exclusions>
<!--版本较低,1.3.0,因此排除-->
<exclusion>
<artifactId>seata-spring-boot-starter</artifactId>
<groupId>io.seata</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>io.seata</groupId>
<artifactId>seata-spring-boot-starter</artifactId>
<!--seata starter 采用1.4.2版本-->
<version>1.4.2</version>
</dependency>
4.书写java代码
Demo例子
A服务(库存)调用B服务(订单)
B服务
@PostMapping
public R<Boolean> add(@RequestBody Demo demo)
{
int i = demoService.insertDemo(demo);
if(i>0){
return R.ok(true);
}else{
return R.fail(false);
}
// return R.fail("我是仓库我内存不足,请添加库存");
}
B服务api(value = "xxxx服务")需要按照自己的实际服务更改
@FeignClient(contextId = "DemoService", value = "xxxx服务", fallbackFactory = DemoFallbackFactory.class)
public interface DemoService {
@PostMapping("/demo")
public R<Boolean> add(@RequestBody DemoNew demo);
}
B服务降级
@Component
public class DemoFallbackFactory implements FallbackFactory<DemoService> {
private static final Logger log = LoggerFactory.getLogger(RemoteBasicDatabaseFallbackFactory.class);
@Override
public DemoService create(Throwable throwable) {
log.error("我是Demo服务请求时间过长请稍后再尝试:{}", throwable.getMessage());
FeignException feignException = (FeignException) throwable;
return new DemoService() {
@Override
public R<Boolean> add(DemoNew demo) {
return R.fail("我是Demo服务请求时间过长请稍后再尝试:" + feignException);
}
};
}
}
需要将B服务暴露的接口放到spring.factoies(Sprimngboot自动装配)
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ com.xxxxxx.api.factory.DemoFallbackFactory
A服务接口
@GlobalTransactional(rollbackFor = Exception.class)
public int updateDemo(Demo demo) throws BusinessException
{
// Demo demo1=new Demo(3l,"我是修改后的库存","4");
//修改dataaq服务在进行调用data服务增加订单操作 然后在那边模拟出现事务
int i = demoMapper.updateDemo(demo);
if(i>0){
System.out.println("修改成功");
}
DemoNew demos=new DemoNew(1l,"我是新增的订单","3");
R<Boolean> add = demoService.add(demos);
if(R.SUCCESS != add.getCode()){
throw new BusinessException(add.getMsg());
}
return 1;
}
- 用到库存表,订单表,seata镜像表
启动各自的服务
如果java在nacos配置的seata信息写错会报错,所以一定的按照规范进行填写
16:56:00.132 [timeoutChecker_2_1] ERROR i.s.c.r.n.NettyClientChannelManager - [reconnect,176] - can not get cluster name in registry config 'service.vgroupMapping.xxxxxx', please make sure registry config correct
16:56:10.094 [timeoutChecker_1_1] ERROR i.s.c.r.n.NettyClientChannelManager - [reconnect,176] - can not get cluster name in registry config 'service.vgroupMapping.xxxxxx', please make sure registry config correct
16:56:10.126 [timeoutChecker_2_1] ERROR i.s.c.r.n.NettyClientChannelManager - [reconnect,176] - can not get cluster name in registry config 'service.vgroupMapping.xxxxxx', please make sure registry config correct
java服务启动成功会在控制台,注册信息提示成功
17:00:14.279 [main] INFO c.a.n.c.r.client - [printIfInfoEnabled,60] - [b44b4993-f7cf-4f68-98b8-a0d1aa30f691] Register server push request handler:com.alibaba.nacos.common.remote.client.RpcClient$ConnectResetRequestHandler
17:00:14.280 [main] INFO c.a.n.c.r.client - [printIfInfoEnabled,60] - [b44b4993-f7cf-4f68-98b8-a0d1aa30f691] Register server push request handler:com.alibaba.nacos.common.remote.client.RpcClient$$Lambda$343/2078396010
1.验证A,B服务都都正常启动
用的是debug模式更方便的查看数据库执行情况,当我没有完全走完代码时候,库存和订单已经生成新数据,undog镜像表也生成一条记录
我代码完全走完时,库存和订单表都完全提交事务,undog的日志也进行删除
2. 验证a服务 i= 1/0模拟,b服务正常启动
可以看到数据库库存和订单表没有修改记录
3.验证a服务正常启动,b服务宕机
可以看到数据库库存和订单表没有修改记录