SpringCloud Aliba-Seata【下】-从入门到学废【8】

目录

1.数据库创建

1.seata_account库下建表

2.seata_order库下建表

3.seata_storage库下建表 

4.在每个库下创建回滚日志 

2.创建订单模块 

2.1建工程

2.2加pom

2.3改yml

2.4file.conf

2.5registry.conf

2.6domain

2.7Dao

2.8Service

2.9controller

2.10config配置

2.11主启动


 

1.数据库创建

  • 这里我们会创建三个服务,一个订单服务,一个库存服务,一个账户服务
  • 当用户下单时,会在订单服务中创建一个订单,然后通过远程调用库存服务来扣减下单商品的库存,再通过远程调用账户服务来扣减用户账户里面的余额,最后在订单服务中修改订单状态为已完成。

1.seata_account库下建表

CREATE TABLE `t_account` (
  `id` int NOT NULL,
  `user_id` int NOT NULL COMMENT '用户id',
  `total` decimal(20,0) NOT NULL COMMENT '总额度',
  `used` decimal(20,0) NOT NULL COMMENT '已用额度',
  `residue` decimal(20,0) NOT NULL COMMENT '剩余可用额度',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci

2.seata_order库下建表

CREATE TABLE `t_order` (
  `id` int NOT NULL,
  `user_id` int NOT NULL COMMENT '用户id',
  `product_id` int NOT NULL COMMENT '产品id',
  `count` int NOT NULL COMMENT '数量',
  `money` decimal(20,0) NOT NULL COMMENT '金额',
  `status` int NOT NULL COMMENT '订单状态:0-创建中,1-已完结',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci

3.seata_storage库下建表 

CREATE TABLE `t_storage` (
  `id` int NOT NULL,
  `product_id` int NOT NULL COMMENT '产品id',
  `total` int NOT NULL COMMENT '总库存',
  `used` int NOT NULL COMMENT '已用库存',
  `residue` int NOT NULL COMMENT '剩余库存',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci

4.在每个库下创建回滚日志 

CREATE TABLE `undo_log` (
  `id` BIGINT(20) NOT NULL AUTO_INCREMENT,
  `branch_id` BIGINT(20) NOT NULL,
  `xid` VARCHAR(100) NOT NULL,
  `context` VARCHAR(128) NOT NULL,
  `rollback_info` LONGBLOB NOT NULL,
  `log_status` INT(11) NOT NULL,
  `log_created` DATETIME NOT NULL,
  `log_modified` DATETIME NOT NULL,
  `ext` VARCHAR(100) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `ux_undo_log` (`xid`,`branch_id`)
) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

2.创建订单模块 

2.1建工程

  • 1.在父工程下创建seata-order-service2001
  • 2.注意jdk和maven版本

2.2加pom


        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <!--mybatis-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
        </dependency>
        <!--druid-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.2.16</version>
        </dependency>
        <!--mysql-connector-java-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <!--jdbc-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.example</groupId>
            <artifactId>cloud-api-commons</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
        <!--springCloud alibaba Naocs-->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
        <!--持久化-->
        <dependency>
            <groupId>com.alibaba.csp</groupId>
            <artifactId>sentinel-datasource-nacos</artifactId>
        </dependency>
        <!--Sentinel-->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
        </dependency>
        <!--openFeign-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
        <!--seata-->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-seata</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>seata-all</groupId>
                    <artifactId>io.seata</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>io.seata</groupId>
            <artifactId>seata-all</artifactId>
            <version>0.9.0</version>
        </dependency>
  

2.3改yml

server:
  port: 2001
spring:
  application:
    name: seata-order-service
  cloud:
    alibaba:
      seata:
        #自定义事务组需要与seat-server中的对应
        tx-service-group: xz_group
    nacos:
      discovery:
        server-addr: 192.168.20.50:1111
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/seata_order
    username: root
    password: 123456

feign:
  sentinel:
    enabled: false

logging:
  level:
    io:
      seata: info

mybatis:
  mapper-locations: classpath:mapper/*.xml

2.4file.conf

在resource下创建文件file.conf,直接粘贴seata的file.conf即可

transport {
  # tcp udt unix-domain-socket
  type = "TCP"
  #NIO NATIVE
  server = "NIO"
  #enable heartbeat
  heartbeat = true
  #thread factory for netty
  thread-factory {
    boss-thread-prefix = "NettyBoss"
    worker-thread-prefix = "NettyServerNIOWorker"
    server-executor-thread-prefix = "NettyServerBizHandler"
    share-boss-worker = false
    client-selector-thread-prefix = "NettyClientSelector"
    client-selector-thread-size = 1
    client-worker-thread-prefix = "NettyClientWorkerThread"
    # netty boss thread size,will not be used for UDT
    boss-thread-size = 1
    #auto default pin or 8
    worker-thread-size = 8
  }
  shutdown {
    # when destroy server, wait seconds
    wait = 3
  }
  serialization = "seata"
  compressor = "none"
}
service {
  #vgroup->rgroup
  vgroup_mapping.my_test_tx_group = "xz_group"
  #only support single node
  default.grouplist = "127.0.0.1:8091"
  #degrade current not support
  enableDegrade = false
  #disable
  disable = false
  #unit ms,s,m,h,d represents milliseconds, seconds, minutes, hours, days, default permanent
  max.commit.retry.timeout = "-1"
  max.rollback.retry.timeout = "-1"
}

client {
  async.commit.buffer.limit = 10000
  lock {
    retry.internal = 10
    retry.times = 30
  }
  report.retry.count = 5
  tm.commit.retry.count = 1
  tm.rollback.retry.count = 1
}

## transaction log store
store {
  ## store mode: file、db
  mode = "db"

  ## file store
  file {
    dir = "sessionStore"

    # branch session size , if exceeded first try compress lockkey, still exceeded throws exceptions
    max-branch-session-size = 16384
    # globe session size , if exceeded throws exceptions
    max-global-session-size = 512
    # file buffer size , if exceeded allocate new buffer
    file-write-buffer-cache-size = 16384
    # when recover batch read size
    session.reload.read_size = 100
    # async, sync
    flush-disk-mode = async
  }

  ## database store
  db {
    ## the implement of javax.sql.DataSource, such as DruidDataSource(druid)/BasicDataSource(dbcp) etc.
    datasource = "dbcp"
    ## mysql/oracle/h2/oceanbase etc.
    db-type = "mysql"
    driver-class-name = "com.mysql.cj.jdbc.Driver"
    url = "jdbc:mysql://127.0.0.1:3306/seata?serverTimezone=UTC"
    user = "root"
    password = "123456"
    min-conn = 1
    max-conn = 3
    global.table = "global_table"
    branch.table = "branch_table"
    lock-table = "lock_table"
    query-limit = 100
  }
}
lock {
  ## the lock store mode: local、remote
  mode = "remote"

  local {
    ## store locks in user's database
  }

  remote {
    ## store locks in the seata's server
  }
}
recovery {
  #schedule committing retry period in milliseconds
  committing-retry-period = 1000
  #schedule asyn committing retry period in milliseconds
  asyn-committing-retry-period = 1000
  #schedule rollbacking retry period in milliseconds
  rollbacking-retry-period = 1000
  #schedule timeout retry period in milliseconds
  timeout-retry-period = 1000
}

transaction {
  undo.data.validation = true
  undo.log.serialization = "jackson"
  undo.log.save.days = 7
  #schedule delete expired undo_log in milliseconds
  undo.log.delete.period = 86400000
  undo.log.table = "undo_log"
}

## metrics settings
metrics {
  enabled = false
  registry-type = "compact"
  # multi exporters use comma divided
  exporter-list = "prometheus"
  exporter-prometheus-port = 9898
}

support {
  ## spring
  spring {
    # auto proxy the DataSource bean
    datasource.autoproxy = false
  }
}

2.5registry.conf

在resource下创建文件registryonf,直接粘贴seata的registry.conf即可

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

  nacos {
    serverAddr = "192.168.20.50:1111"
    namespace = ""
    cluster = "default"
  }
  eureka {
    serviceUrl = "http://localhost:8761/eureka"
    application = "default"
    weight = "1"
  }
  redis {
    serverAddr = "localhost:6379"
    db = "0"
  }
  zk {
    cluster = "default"
    serverAddr = "127.0.0.1:2181"
    session.timeout = 6000
    connect.timeout = 2000
  }
  consul {
    cluster = "default"
    serverAddr = "127.0.0.1:8500"
  }
  etcd3 {
    cluster = "default"
    serverAddr = "http://localhost:2379"
  }
  sofa {
    serverAddr = "127.0.0.1:9603"
    application = "default"
    region = "DEFAULT_ZONE"
    datacenter = "DefaultDataCenter"
    cluster = "default"
    group = "SEATA_GROUP"
    addressWaitTime = "3000"
  }
  file {
    name = "file.conf"
  }
}

config {
  # file、nacos 、apollo、zk、consul、etcd3
  type = "file"

  nacos {
    serverAddr = "localhost"
    namespace = ""
  }
  consul {
    serverAddr = "127.0.0.1:8500"
  }
  apollo {
    app.id = "seata-server"
    apollo.meta = "http://192.168.1.204:8801"
  }
  zk {
    serverAddr = "127.0.0.1:2181"
    session.timeout = 6000
    connect.timeout = 2000
  }
  etcd3 {
    serverAddr = "http://localhost:2379"
  }
  file {
    name = "file.conf"
  }
}

2.6domain

  • 1.创建封装类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class CommonResult<T> {
    private Integer code;
    private String message;
    private  T data;
    public CommonResult(Integer code,String message){
        this.code=code;
        this.message=message;
    }
}
  • 2.创建实体类 
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class Order {
    private Integer id;
    private Integer userId;
    private Integer productId;
    private Integer count;
    private BigDecimal money;
    private Integer status;
}

2.7Dao

@Mapper
public interface OrderDao {

    //1.新建订单
    void create(Order order);

    //2.修改订单状态;从0到1
    void update(@Param("userId") Integer userId, @Param("status") Integer status);

}

2.8Service

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Resource
    private OrderDao orderDao;
    @Resource
    private StorageService storageService;
    @Resource
    private AccountService accountService;

    @Override
    @GlobalTransactional(name = "xz_create_order",rollbackFor = Exception.class)
    public void create(Order order) {
        //1.新建订单
        log.info("====开始新建订单====");
        orderDao.create(order);

        //2.扣减库存
        log.info("====订单微服务开始调用库存,扣减count====start");
        storageService.decrease(order.getProductId(),order.getCount());
        log.info("====订单微服务开始调用库存,扣减count====end");

        //3.扣减账户
        log.info("====订单微服务开始调用账户,扣减money====start");
        accountService.decrease(order.getUserId(),order.getMoney());
        log.info("====订单微服务开始调用账户,扣减money====end");

        //4.修改订单状态
        log.info("====开始修改订单状态====start");
        orderDao.update(order.getUserId(),0);
        log.info("====开始修改订单状态====end");

        log.info("====下订单结束====");
    }
}
  • 使用openfeign创建AccountService 
@FeignClient(value = "seata-account-service")
public interface AccountService {

    @PostMapping(value = "/storage/decrease")
    CommonResult decrease(@RequestParam("userId")Integer userId,@RequestParam("money") BigDecimal money);
}
  • 使用openfeign创建StorageService 
@FeignClient(value = "seata-storage-service")
public interface StorageService {

    @PostMapping(value = "/storage/decrease")
    CommonResult decrease(@RequestParam("productId")Integer productId,@RequestParam("count")Integer count);
}

2.9controller

@RestController
public class OrderController {

    @Resource
    private OrderService orderService;


    @GetMapping("/order/create")
    public CommonResult<Order> create(Order order){
        orderService.create(order);
        return new CommonResult<>(200,"订单创建成功");
    }
}

2.10config配置

@Configuration
public class DataSourceConfig {

    @Value("${mybatis.mapper-locations}")
    private String mapperLocations;

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource dataSource(){
        return new DruidDataSource();
    }

    @Bean
    public DataSourceProxy dataSourceProxy(DataSource dataSource){
      return new DataSourceProxy(dataSource);
    }

    @Bean
    public SqlSessionFactory sqlSessionFactory(DataSourceProxy dataSourceProxy)throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean=new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSourceProxy);
        sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(mapperLocations));
        sqlSessionFactoryBean.setTransactionFactory(new SpringManagedTransactionFactory());
        return sqlSessionFactoryBean.getObject();
    }
}
@Configuration
@MapperScan("com.xz.springcloud.dao")
public class MybatisConfig {
}

2.11主启动

@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
@EnableFeignClients
@EnableDiscoveryClient
public class SeataOrderMainApp2001 {
    public static void main(String[] args) {
        SpringApplication.run(SeataOrderMainApp2001.class);
    }
}

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:/a/349958.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

阅读go语言工具源码系列之gopacket(谷歌出品)----第一集 DLL的go封装

gopacket项目是google出品的golang第三方库&#xff0c;项目源码地址google/gopacket: Provides packet processing capabilities for Go (github.com) gopacket核心是对经典的抓包工具libpcap(linux平台)和npcap(windows平台)的go封装&#xff0c;提供了更方便的go语言操作接…

36、WEB攻防——通用漏洞XSS跨站MXSSUXSSFlashXSSPDFXSS

文章目录 MXSSUXSSFlashXSSPDF XSS 跨站的艺术-XSS入门与介绍 UTF-7 XSS、MHTML XSS、CSS XSS、VBScript XSS已经过时&#xff0c;基本上不会出现。 MXSS 简单来说&#xff0c;就是你往前端页面插入payload&#xff0c;但是前端有些防御策略会将payload编码&#xff0c;导致…

防火墙综合实验

实验需求&#xff1a; 1、生产区在工作时间内可以访问服务器区&#xff0c;仅可以访问http服务器。 2、办公区全天可以访问服务器区&#xff0c;其中&#xff0c;10.0.2.20可以访问FTP服务器和HTTP服务器&#xff0c;10.0.2.10仅可以ping通10.0.3.10。 3、办公区在访问服务器…

【VBA代码解决方案】md文档转Word后,全自动转换为标准的Word公式格式

【VBA解决方案】全自动将Word中的文本公式转换为标准公式 写在最前面VBA代码全自动方法将md文档导出为word代码如何运行VBA代码注意事项 一些如何实现的回忆记录步骤解析手动将文本转换为Word公式代码逻辑步骤设想代码解析代码解释总结 其他背景介绍应用场景VBA脚本介绍如何使用…

信息安全认证首选CISP-PTE

&#x1f525;在信息安全领域&#xff0c;CISP-PTE认证正逐渐成为行业的新星。作为中国信息安全测评中心推出的专业认证&#xff0c;CISP-PTE为信息安全从业者提供了国内Z高标准的资质培训。 &#x1f3af;为什么选择CISP-PTE&#xff1f; 1️⃣业界认可&#xff1a;CISP-PTE是…

JAVA_EE_api_中英文对照版

点击即可下载&#xff1a; JAVA_EE_api_中英文对照版

STM32标准库——(3)GPIO输入

1.按键简介 按键&#xff1a;常见的输入设备&#xff0c;按下导通&#xff0c;松手断开 按键抖动&#xff1a;由于按键内部使用的是机械式弹簧片来进行通断的&#xff0c;所以在按下和松手的瞬间会伴随有一连串的抖动 1.1 硬件电路图 上面两个是外加上拉电阻&#xff08;常用…

Python学习从0到1 day9 Python函数

苦难是花开的伏笔 ——24.1.25 函数 1.定义 函数&#xff1a;是组织好的&#xff0c;可重复使用的&#xff0c;用来实现特定功能的代码段 2.案例 在pycharm中完成一个案例需求&#xff1a;不使用内置函数len&#xff08;&#xff09;&#xff0c;完成字符串长度的计算 #统计字…

MyBatis 批量插入数据优化

前言 最近在项目上遇到了批量插入的场景问题&#xff0c;由于每次需要插入超过 10w 的数据量并且字段也蛮多的导致如果使用循环单次插入的方式插入数据插入的效率不高。相信读者们在实际开发中也遇到过这样类似的场景&#xff0c;那么批量插入如何实现呢&#xff1f; 其实我也…

分寝室

L1-7 分寝室 分数 20 作者 陈越 单位 浙江大学 学校新建了宿舍楼&#xff0c;共有 n 间寝室。等待分配的学生中&#xff0c;有女生 n0​ 位、男生 n1​ 位。所有待分配…

Vue使用svg图片-svg-sprite-loader插件

需求&#xff1a;设计给的一个按钮图标是svg的&#xff0c;不是element自带的图标使用插件svg-sprite-loader svg-sprite-loader 什么是svg-sprite-loader&#xff1f; 将多个 svg 打包成 svg-sprite。svg 雪碧图。类似于 CSS 中的 Sprite 技术。图标图形整合在 一起&#xf…

爆火《幻兽帕鲁》被指用AI缝合宝可梦,开发者自曝传奇经历:是人类的奇迹

梦晨 克雷西 发自 凹非寺 量子位 | 公众号 QbitAI 4天卖出600万份&#xff0c;爆火游戏《幻兽帕鲁》最高180万人同时在线&#xff0c;直接登顶。 这个成绩&#xff0c;甚至在整个Steam游戏平台历史上也能排到第二&#xff0c;连平台自家王牌CS2都被挤下去了。 同时&#xff0…

NGINX如何实现rtmp推流服务

最近直播大火&#xff0c;直播推流软件遍地开花&#xff0c;那么用NGINX如何进行推流呢&#xff1f;下面我们就简单的介绍一下用NGINX的rtmp模块如何实现视频推流&#xff0c;我们主要从一下几点介绍&#xff1a; 推流拉流推流认证拉流认证 package mainimport ("fmt&qu…

[MQ]常用的mq产品图形管理web界面或客户端

一、MQ介绍 1.1 定义 MQ全称为Message Queue&#xff0c;消息队列是应用程序和应用程序之间的通信方法。 如果非要用一个定义来概括只能是抽象出来一些概念&#xff0c;概括为跨服务之间传递信息的软件。 1.2 MQ产品 较为成熟的MQ产品&#xff1a;IBMMQ&#xff08;IBM We…

公司内网虚拟机中穿透服务器Coturn的搭建

1. 写在前面 coturn服务器的搭建文章已经非常多&#xff0c;但是对于对linux不熟悉的人来说排查错误的文章不多&#xff0c;此篇文章把我这次搭建过程以及如何排查问题做一个梳理我这里是在oracle vm虚拟机中搭建安装的ubuntu&#xff0c;通过H3C路由器映射到外网以下介绍我只…

SpringBoot的默认组件扫描

本篇博客主要探究&#xff1a;为什么SpringBoot项目中我们没有配置组件扫描的包&#xff0c;为什么它会默认扫描启动类所在的包&#xff1f; 一、访问与启动类所在同一包下的接口 我们先来看一个简单的接口&#xff1a; 我们可以观察到&#xff0c;HelloController这个类处在…

Linux中LVM实验

LVM实验&#xff1a; 1、分区 -L是大小的意思-n名称的意思 从vg0&#xff08;卷组&#xff09;分出来 2、格式化LV逻辑卷 LVM扩容 如果icdir空间不够了&#xff0c; 扩展空间lvextend -L 5G /dev/vg0/lv1 /dev/vg0/lv1(pp,vg,lv) 刷新文件系统xfs_growfs /lvdir VG扩容 …

阿里云快速搭建《幻兽帕鲁》服务器自建指南

如何自建幻兽帕鲁服务器&#xff1f;基于阿里云服务器搭建幻兽帕鲁palworld服务器教程来了&#xff0c;一看就懂系列。本文是利用OOS中幻兽帕鲁扩展程序来一键部署幻兽帕鲁服务器&#xff0c;阿里云百科aliyunbaike.com分享官方基于阿里云服务器快速创建幻兽帕鲁服务器教程&…

【华为云-云驻共创】数据高速公路—数仓集群通信技术详解

【摘要】本文讲解GaussDB&#xff08;DWS&#xff09;集群通信技术如何在大规模集群中承载高并发业务&#xff0c;如何实现高性能分布式通信系统。主要讲述客户端、CN、DN三类进程间的通信原理和流程&#xff0c;分为CN通信框架和DN间通信框架。 数据仓库服务GaussDB&#xff0…

伊恩·斯图尔特《改变世界的17个方程》薛定谔方程笔记

想法是等这学期学到薛定谔方程后再把整份完善下。 它告诉我们什么&#xff1f; 这个方程不是把物质作为粒子&#xff0c;而是作为波&#xff0c;并描述这样的波如何传播。 为什么重要&#xff1f; 薛定谔方程是量子力学的基础&#xff0c;它与广义相对论一起构成了当今最有效的…