Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to implement the alibaba seata server

2025-01-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article is to share with you how to implement the alibaba seata server. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

What is seata?

Seata is used to deal with the transaction of mutual invocation between distributed services.

Seata terminology

TC (Transaction Coordinator)-transaction coordinator

Maintain the state of global and branch transactions and drive global transaction commit or rollback.

TM (Transaction Manager)-transaction manager

Define the scope of the global transaction: start the global transaction, commit or roll back the global transaction.

RM (Resource Manager)-Resource Manager

Manage resources for branch transactions, talk to TC to register branch transactions and report the status of branch transactions, and drive branch transactions to commit or rollback.

Seata Chinese document: what is Seata

Seata download address: https://github.com/seata/seata/releases

The concrete implementation of seata server

I downloaded 1.3.0.

Directory structure after decompression

Modify configuration file: registry.conf registration information. Type defaults to file. I want to register with nacos and modify the nacos configuration information.

Registry {# file 、 nacos 、 eureka 、 redis 、 zk 、 consul 、 etcd3 、 Sofa type = "nacos" nacos {application = "seata-server" serverAddr = "127.0.0.1 nacos 3333" group = "SEATA_GROUP" namespace = "cluster =" default "username =" nacos "password =" nacos "} eureka {serviceUrl =" http://localhost:8761/eureka" application = "default" weight = "1"} redis {serverAddr = "localhost:6379" db = 0 password = "" cluster = "default" timeout = 0} zk {cluster = "default" serverAddr = "127.0.0.1 username 2181" sessionTimeout = 6000 connectTimeout = 2000 username = "" password = ""} consul {cluster = "default" serverAddr = "127.0.0.1 default 8500"} etcd3 {cluster = "default" serverAddr = "http://localhost:2379"} Sofa {serverAddr = "127.0.0.1 default 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 = "127.0.0.1serverAddr 8848" namespace = "" group = "SEATA_GROUP" username = "" password = ""} consul {serverAddr = "127.0.0.1 nacos 8500"} apollo {appId = "seata-server" apolloMeta = "http://192.168.1.204:8801" namespace =" application "} zk {serverAddr = "127.0.0.1 connectTimeout 2181" sessionTimeout = 6000 connectTimeout = 2000 username = "" password = ""} etcd3 {serverAddr = "http://localhost:2379"} file {name =" file.conf "}}

File.conf configuration database information, here I configure db. To create a new database. Add four tables.

Branch_table 、 global_table 、 lock_table 、 undo_log . Version 1.3.0 did not give us sql. Other versions of sql are written below.

# # transaction log store, only used in seata-serverstore {# # store mode: file, db, redis mode = "db" # # file store property file {# # store location dir dir = "sessionStore" # branch session size, if exceeded first try compress lockkey, still exceeded throws exceptions maxBranchSessionSize = 16384 # globe session size, if exceeded throws exceptions maxGlobalSessionSize = 512 # file buffer size, if exceeded allocate new buffer fileWriteBufferCacheSize = 16384 # when recover batch read size sessionReloadReadSize = 100 # async Sync flushDiskMode = async} # # database store property db {# # the implement of javax.sql.DataSource Such as DruidDataSource (druid) / BasicDataSource (dbcp) / HikariDataSource (hikari) etc. Datasource = "druid" # # mysql/oracle/postgresql/h3/oceanbase etc. DbType = "mysql" driverClassName = "com.mysql.cj.jdbc.Driver" url = "jdbc:mysql://127.0.0.1:3306/seata?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8" user = "root" password = "123456" minConn = 5 maxConn = 30 globalTable = " Global_table "branchTable =" branch_table "lockTable =" lock_table "queryLimit = 5000} # # redis store property redis {host =" 127.0.0.1 "port =" 6379 "password =" database = "0" minConn = 1 maxConn = 10 queryLimit = 100}

Sql

SET NAMES utf8mb4;SET FOREIGN_KEY_CHECKS = 0;-Table structure for branch_table-- DROP TABLE IF EXISTS `branch_ table` CREATE TABLE `branch_ Table` (`resource_group_ id` bigint (20) NOT NULL, `xid` varchar (128CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL), `transaction_ id` bigint (20) DEFAULT NULL, `resource_group_ id` varchar (32) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL, `resource_ id` varchar (256) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL, `branch_ type` varchar (8) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL, `status` tinyint (4) DEFAULT NULL `gmt_ id` varchar (64) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL, `application_ data` varchar (2000) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL, `gmt_ create` datetime (6) DEFAULT NULL, `gmt_ modified` datetime (6) DEFAULT NULL, PRIMARY KEY (`branch_ id`) USING BTREE, INDEX `idx_ xid` (`xid`) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic -Table structure for global_table-- DROP TABLE IF EXISTS `global_ table` CREATE TABLE `global_ table`, `transaction_ id` bigint (20) DEFAULT NULL, `status` tinyint (4) NOT NULL, `application_ id` varchar (32) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL, `transaction_service_ group` varchar (32) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL, `transaction_ name` varchar (128) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL, `timeout` int (11) DEFAULT NULL, `begin_ time` bigint (20) DEFAULT NULL `gmt_ data` varchar (2000) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL, `gmt_ create` datetime (0) DEFAULT NULL, `gmt_ modified` datetime (0) DEFAULT NULL, PRIMARY KEY (`xid`) USING BTREE, INDEX `idx_gmt_modified_ status` (`gmt_ modified`, `status`) USING BTREE, INDEX `idx_transaction_ id` (`transaction_ id`) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic -Table structure for lock_table-- DROP TABLE IF EXISTS `lock_ table` CREATE TABLE `lock_ Table` (`row_ key` varchar (12828) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL, `xid` varchar (96) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL, `transaction_ id` bigint (20) DEFAULT NULL, `branch_ id` bigint (20) NOT NULL, `resource_ id` varchar (256) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL, `table_ name` varchar (32) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL, `pk` varchar (36) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL `Create` datetime (0) DEFAULT NULL, `gmt_ modified` datetime (0) DEFAULT NULL, PRIMARY KEY (`row_ key`) USING BTREE, INDEX `idx_branch_ id` (`branch_ id`) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic -Table structure for undo_log---DROP TABLE IF EXISTS `undo_ log` CREATE TABLE `undo_ log` (`id` bigint (20) NOT NULL AUTO_INCREMENT, `branch_ id` bigint (20) 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 (11) NOT NULL, `log_ created` datetime (0) NOT NULL, `log_ modified` datetime (0) NOT NULL, `ext` varchar (100) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT 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

Start your own nacos registry.

Then double-click the seata-server.bat file in the bin directory to start.

If you look at the nacos registry and find that there is a seata service, it is a success.

Seata client

Pom file

4.0.0 spring-cloud-demo com.xx.job 1.0-SNAPSHOT seata-order-service2001 1.8 com.xx.job cloud-common ${project.version} mysql mysql-connector-java org.mybatis.spring.boot Mybatis-spring-boot-starter 2.0.0 org.springframework.boot spring-boot-starter-data-jpa com.alibaba druid spring-boot-starter-web spring-boot-starter-test test junit junit 4.11 spring-boot-starter-actuator Com.alibaba.cloud spring-cloud-starter-alibaba-nacos-discovery spring-cloud-starter-alibaba-nacos-config org.springframework.cloud spring-cloud-starter-openfeign io.seata seata-all org.projectlombok lombok org.springframework.boot Spring-boot-maven-plugin org.apache.maven.plugins maven-compiler-plugin 6 6

Yml file

Server: port: 2001 spring: application: name: seata-order-service cloud: nacos: discovery: server-addr: 127.0.0.1:3333 config: file-extension: yml datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://127.0.0.1:3306/order?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8 username: root password: 123456 type: com .alibaba.druid.pool.DruidDataSourcemybatis: type-aliases-package: com.xx.job.entity mapper-locations: classpath:mapper/*.xml#==Seata Config===seata: enabled: true application-id: account-seata-example tx-service-group: account-service-seata-service-group # transaction group (each application can be named independently You can also use the same name) client: rm-report-success-enable: true rm-table-meta-check-enable: false # automatically refresh the table structure in the cache (default false) rm-report-retry-count: 5 # Phase 1 result report TC retries (default 5) rm-async-commit-buffer-limit: 10000 # Asynchronous commit cache queue length (default 10000) rm: Lock: lock-retry-internal: 10 # check or occupy the global lock retry interval (default 10ms) lock-retry-times: 30 # check or occupy the number of global lock retries (default 30) lock-retry-policy-branch-rollback-on-conflict: true # when the branch transaction conflicts with other global rollback transactions (release the local lock first to allow the rollback to succeed) Tm-commit-retry-count: number of TC retries reported to the global submission result of phase 3 # (default is 1) It is recommended to be greater than 1) tm-rollback-retry-count: the number of TC retries reported to the global rollback result of phase 3 # (default is 1) It is recommended to be greater than 1) undo: undo-data-validation: true # two-stage rollback image check (default true enabled) undo-log-serialization: jackson # undo serialization method (default jackson) undo-log-table: undo_log # custom undo table name (default undo_log) log: exceptionRate: 100 # log exception output probability (default 100) support: Spring: datasource-autoproxy: true service: vgroup-mapping: my_test_tx_group: default # TC cluster (must be consistent with seata-server) enable-degrade: false # downgrade switch disable-global-transaction: false # disable global transactions (default false) grouplist: default: 127.0.0.1 false 8091 transport: shutdown: wait: 3 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 type: TCP server: NIO heartbeat: true serialization: seata compressor: none enable-client-batch-send-request: true # whether the client transaction message request is sent in bulk (default true) registry: file: name: file.conf type: nacos server-addr: localhost:3333 namespace: cluster: default config:

The business code needs to add two annotations, local and distributed.

@ Transactional@GlobalTransactionalpackage com.xx.job.seataorderservice2001.controller; import com.xx.job.common.CommonResult;import com.xx.job.entity.Account;import com.xx.job.entity.Order;import com.xx.job.entity.Storage;import com.xx.job.seataorderservice2001.service.AccountService;import com.xx.job.seataorderservice2001.service.OrderService;import com.xx.job.seataorderservice2001.service.StorageSerivce;import io.seata.spring.annotation.GlobalTransactional;import lombok.extern.slf4j.Slf4j;import org.springframework.beans.factory.annotation.Autowired Import org.springframework.transaction.annotation.Transactional;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;@Slf4j@RestControllerpublic class OrderController {@ Autowired private OrderService orderService; private AccountService accountService; private StorageSerivce storageSerivce / * * add order minus balance reduce inventory * @ param order * @ return * / @ Transactional @ GlobalTransactional @ RequestMapping ("/ order/create") public CommonResult create (Order order) {/ / add order orderService.create (order); / / reduce balance Account account = new Account (); account.setUserId (order.getUserId ()) Account.setMoney (80); accountService.update (account); / / inventory reduction Storage storage = new Storage (); storage.setCount (999); storage.setCommodityCode (order.getCommodityCode ()); storageSerivce.update (storage); return new CommonResult (200, "order added successfully!") Thank you for reading! This is the end of the article on "how to implement the alibaba seata server". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report