学习分布式事务springboot+nacos+seata

今天学习seata,也踩了很多坑,老折磨王了,来总结一下
感谢https://blog.csdn.net/ZaiZuoYuZuo/article/details/107636180
大佬的文章

下载seata

https://github.com/seata/seata/releases

创建日志表

CREATE TABLE IF NOT EXISTS `undo_log`
(
    `branch_id`     BIGINT(20)   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(11)      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
  AUTO_INCREMENT = 1
  DEFAULT CHARSET = utf8 COMMENT ='AT transaction mode undo table';

我的理解啊 seata通过日志和反向sql语句来实现回滚操作

解压并修改配置文件

在conf文件中创建config.txt 内容为

service.vgroupMapping.my_test_tx_group=default
store.mode=db
store.db.datasource=druid
store.db.dbType=mysql
store.db.driverClassName=com.mysql.cj.jdbc.Driver
store.db.url=jdbc:mysql://你的数据库地址: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.queryLimit=100
store.db.lockTable=lock_table
store.db.maxWait=5000

创建acos-config.sh脚本,用于把config.txt同步到nacos中

#!/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

执行nacos-config.sh脚本
因为我是windows系统所以前面没有sh

nacos-config.sh -h //nacos地址

成功后查看配置中心
在这里插入图片描述
这里我踩了个坑因为我的数据库密码第一位有个+号,nacos会把+转译成空格,所以我一直报一个奇怪的错误
Could not retrieve transation read-only status server
说我的数据库权限为只读,折磨了我好久,所以执行完可以在nacos中查看一下

修改conf/registry.conf文件

registry {
  # file 、nacos 、eureka、redis、zk、consul、etcd3、sofa
  type = "nacos"

  nacos {
    application = "seata-server"
    serverAddr = "127.0.0.1:8848"
    group = "SEATA_GROUP"
    namespace = ""
    cluster = "default"
    username = ""
    password = ""
  	}
  }
  config {
  # file、nacos 、apollo、zk、consul、etcd3
  type = "nacos"

  nacos {
    serverAddr = "127.0.0.1:8848"
    namespace = ""
    group = "SEATA_GROUP"
    username = ""
    password = ""
  	}
  }

启动seata-server.bat

Linux sh seata-server.sh -p 8091 -h 127.0.0.1
因为我是windows系统 就双击啦

引入依赖

<exclusions>
                <exclusion>
                    <groupId>io.seata</groupId>
                    <artifactId>seata-all</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>io.seata</groupId>
                    <artifactId>seata-spring-boot-starter</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>io.seata</groupId>
            <artifactId>seata-spring-boot-starter</artifactId>
            <version>${seata.version}</version>
        </dependency>

在微服务项目中修改配置文件yml

seata:
  enabled: true
  application-id: ${spring.application.name}
  tx-service-group: my_test_tx_group
  config:
    type: nacos
    nacos:
      namespace:
      serverAddr: nacos地址:8848
      group: SEATA_GROUP
      userName: ""
      password: ""
  registry:
    type: nacos
    nacos:
      application: seata-server
      serverAddr: nacos地址:8848
      group: SEATA_GROUP
      namespace:
      userName: ""
      password: ""

添加数据源

package com.xfdc.nacos.config;


import com.zaxxer.hikari.HikariDataSource;
import io.seata.rm.datasource.DataSourceProxy;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;


/**
 * @author Administrator
 */
@Configuration
public class DataSourceProxyAutoConfiguration {
    private DataSourceProperties dataSourceProperties;

    public DataSourceProxyAutoConfiguration (DataSourceProperties dataSourceProperties){
        this.dataSourceProperties = dataSourceProperties;
    }
    @Primary
    @Bean("dataSource")
    public DataSource dataSource() {
        HikariDataSource dataSource = new HikariDataSource();
        dataSource.setJdbcUrl(dataSourceProperties.getUrl());
        dataSource.setUsername(dataSourceProperties.getUsername());
        dataSource.setPassword(dataSourceProperties.getPassword());
        dataSource.setDriverClassName(dataSourceProperties.getDriverClassName());
        return new DataSourceProxy(dataSource);
    }
}

在全局事务的接口方法上添加@GlobalTransactional

先修改数据,然后删除。如果修改失败则回滚数据不删除
在删除接口中添加报错的代码5/0
让他有些延迟号看他修改和回滚的操作
在这里插入图片描述

在这里插入图片描述

老折磨王了 啊这

再度感谢https://blog.csdn.net/ZaiZuoYuZuo/article/details/107636180

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
使用 Spring BootSpring Cloud Alibaba Seata 实现分布式事务需要以下步骤: 1. 添加依赖:在 pom.xml 中添加 seata-all 和 seata-spring-boot-starter 依赖。 2. 配置 Seata:在 application.properties 或 application.yml 中配置 Seata Server 的地址和端口,以及各个事务组的配置信息。 3. 配置数据源代理:使用 Seata 提供的数据源代理,将原本的数据源替换为 Seata 提供的代理数据源。 4. 配置分布式事务注解:在需要进行分布式事务的方法上添加 @GlobalTransactional 注解。 下面是一个示例 application.yml 配置文件: ```yaml spring: datasource: url: jdbc:mysql://localhost:3306/test username: root password: root driver-class-name: com.mysql.jdbc.Driver seata: enabled: true application-id: demo-app tx-service-group: my_tx_group config: type: nacos nacos: serverAddr: localhost:8848 namespace: public service: vgroupMapping: my_test_tx_group: default groupMapping: my_test_tx_group: "DEMO_GROUP" datasources: ds: driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://localhost:3306/test username: root password: root type: com.alibaba.druid.pool.DruidDataSource maxPoolSize: 20 minPoolSize: 1 initialSize: 1 maxLifetime: 1800000 validationQuery: select 1 validationQueryTimeout: 30000 testOnBorrow: true testWhileIdle: true testOnReturn: false ``` 在代码中使用 @GlobalTransactional 注解: ```java @Service public class OrderServiceImpl implements OrderService { @Autowired private OrderMapper orderMapper; @Autowired private AccountClient accountClient; @Autowired private StorageClient storageClient; @GlobalTransactional @Override public void create(Order order) { // 1. 创建订单 orderMapper.create(order); // 2. 扣减库存 storageClient.deduct(order.getProductId(), order.getCount()); // 3. 扣减账户余额 accountClient.deduct(order.getUserId(), order.getMoney()); // 4. 修改订单状态 orderMapper.update(order.getUserId(), 0); } } ``` 其中,AccountClient 和 StorageClient 是通过 Feign 实现的远程调用,这些服务也需要添加 Seata 的依赖和配置。 这样就可以实现分布式事务了。
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值