Make writing a habit together! This is the 11th day of my participation in the “Gold Digging Day New Plan · April More text Challenge”. Click here for more details.

Springcloud + NACOS + SEATA project integration

1. Environment preparation

1.1 nacos1.3.2 and seata1.3.0 preparations

  • Nacos document
  • Seata document
  • Nacos1.3.2 Download address
  • Seata1.3.0 download address
  • Config.txt address for seata1.3.0 (configuration parameters required for seATA service startup)
  • Nacos-config. sh address for seata1.3.0 (script to import config.txt to nacos configuration center in Linux)
  • Nacos-config. py address for Seata1.3.0 (window import config.txt into nacOS configuration center script)
  • Mysql.sql address for Seata 1.3.0 (database file required for seATA service)

1.2 NacOS and SEATA configuration and startup

Rename the decompressed NACOS to nacOS-server. Rename the decompressed SeATA to seata-serverCopy the code
  • Start the nacos
CMD file to change set MODE="cluster" to set MODE="standalone", indicating the standalone MODECopy the code
Windows start command, double-click startup. CMD in nacos-server/binCopy the code
Run the sh shutdown.sh command nacos-server/bin command to start LinuxCopy the code
  • Prepare seata
Py, nacos-config.sh, and mysql. SQL in the seata-server/conf directoryCopy the code
  • Create the SEATA database
In the local mysql database server, create a database named seata. Then execute the mysql. SQL file in the database to create the seATA related tables.Copy the code
  • Import the config.txt configuration into the NACOS configuration center
Modify store.db.url and store.db.user and store.db.password for the newly created SEata database configuration: My_test_tx_group =default my_test_tx_group indicates the transaction group. My_test_tx_group indicates the group. The value of the configuration item is the name of the TC cluster.  service.vgroupMapping.order-service-group=default service.vgroupMapping.storage-service-group=defaultCopy the code
Run python nacos-config.py 127.0.0.1:8848 (note: If there is a Python environment, if no, manually add it to the NACOS configuration center (♥, ‿ ‿, subsisting)) Linux, push config. TXT to the nacos command: sh nacos-config.sh -h 127.0.0.1 -p 8848Copy the code
  • Modify the seATA configuration

    • Since you are using NACOS and DB, you can delete the file file.conf under seata-server/conf
    • Modify the registry. Conf file under seata-server/conf
    Registry {# file, nacos, Eureka, Redis, ZK, Consul, ETCD3, SOFA type = "nacos" nacos {application = "seata-server" ServerAddr = "127.0.0.1:8848" # select * from serverAddr = "127.0.0.1:8848" # select * from serverAddr Namespace = "" cluster = "default" username = "" password = ""}} config {# file, nacos, Apollo, Zk, Consul, etCD3 type = "Nacos" nacOS {serverAddr = "127.0.0.1" namespace = "" group = "SEATA_GROUP" username = "" password = ""}}Copy the code
    • Modify JVM memory configuration. Bat and. Sh files in seata-server/bin
     %JAVACMD% %JAVA_OPTS% -server -Xmx512m -Xms512m -Xmn512m -Xss512k 
    Copy the code
  • Start the Seata service

Window start command, double-click seata-server.bat in seata-server/binCopy the code
Run the sh seata-server.sh -p 8091 -h 127.0.0.1 command to start LinuxCopy the code
2. Springcloud nacos – seata

The official demo

1. Prepare AT mode for the database

On the local mysql database server, execute the database. SQL file to create seata-order and Seata-storage databases.Copy the code

2. Configure a registry. Conf file in each application resource, which is the same as that in seata-server

Each configuration item application. Yml, pay attention to the spring. Cloud. Alibaba. Seata. Tx - service - group service group name, This parameter corresponds to service.vgroup_mapping.${your-service-gruop} configured in config. TXTCopy the code

3. Application. Yml configuration

Discovery: server-addr: 127.0.0.1:8848 Alibaba: seata: tx-service-group: ${spring.application.name}-groupCopy the code

4. Enable global transactions

Use the @GlobalTransactional annotation on the service caller. (Non-intrusive (♥, ‿ ‿)) Using SEATA AT mode, that is, two-phase submission Evolution of the two-phase submission protocol: Phase one: service data and rollback logs are recorded in the same local transaction to release the local lock and connection resources. Phase two: Commit asynchronously, done very quickly. Rollback is compensated in reverse by the rollback log of one phase.Copy the code
/** * Order: Create orders, reduce inventory, There are two services involved * * @param userId * @param commodityCode * @param count */ @globalTransactional @Transactional(rollbackFor = Exception.class) public void placeOrder(String userId, String commodityCode, Integer count) { BigDecimal orderMoney = new BigDecimal(count).multiply(new BigDecimal(5)); Order order = new Order() .setUserId(userId) .setCommodityCode(commodityCode) .setCount(count) .setMoney(orderMoney); orderDAO.insert(order); storageFeignClient.deduct(commodityCode, count); }Copy the code
Note: SEATA also supports TCC mode, TCC is supported by Ant Financial, know it all (♥, ‿ negotiating). Performance optimization: TCC mode has higher performance than AT mode despite code intrusion.Copy the code

5. Test

Distributed transaction is successful, to simulate normal orders, inventory localhost: 9091 / order/placeOrder/commit distributed transaction failure, simulation order success, buckle inventory failure, The final rollback localhost: 9091 / order/placeOrder/rollbackCopy the code

Principle 6.

Transaction Coordinator (TC) - The Transaction Coordinator maintains the status of global and branch transactions and drives global transactions to be committed or rolled back. TM (Transaction Manager) - The Transaction Manager defines the scope of a global Transaction: start, commit, or roll back the global Transaction. Resource Manager (RM) - The Resource Manager manages the resources for branch transaction processing, talks with TCS to register branch transactions and report the status of branch transactions, and drives branch transactions to commit or roll back.Copy the code

1. TM applies to TC for starting a global transaction. The global transaction is successfully created and a globally unique XID is generated. 2. XID is propagated in the context of the microservice invocation link. 3. RM registers branch transactions with TC and adds them to the jurisdiction of the global transaction corresponding to XID. 4. TM initiates a global commit or rollback resolution against XID to TC. 5. TC schedules all branch transactions under XID to complete the submission or rollback request.Copy the code
  • Seata phase one loading
  • Seata phase 2 commit
  • Seata Two-phase rollback

The default global isolation level for Seata (AT mode) is Read Uncommitted;

7. Set up the SEATA cluster

Run the./seata-server.sh -p 18091 -n 1 command to start the first TC server. -p: indicates the port monitored by the Seata TC Server. -n: Server node. If multiple TC Servers are deployed, the nodes must be identified to generate transaction ids of different ranges to avoid conflicts. Run the./seata-server.sh -p 28091 -n 2 command to start the second TC server.Copy the code

8. TCC mode

A distributed global transaction is a two-phase commit (Try - [Comfirm/Cancel]) model. In Seata, both AT mode and TCC mode are actually based on two-phase commit. The difference is that AT mode is based on a relational database that supports local ACID transactions: 1. Prepare in phase 1: Both service data update and corresponding rollback log are submitted in the local transaction. 2. Phase-2 COMMIT behavior: The rollback logs are automatically cleared asynchronously and in batches immediately. 3. Phase-2 Rollback: Data is rolled back using rollback logs to automatically generate compensation operations. In TCC mode, we need to write code to implement the commit and rollback. 1. Insert order, update inventory, update balance. 3. Phase-2 Rollback behavior: Call the customized rollback logic; Therefore, TCC mode is to integrate the commit and rollback of custom branch transactions into global transaction management. In layman's terms, Seata's TCC mode is a manual version of THE AT mode. It allows you to customize the two-phase processing logic without relying on the UNdo_log rollback table of the AT mode.Copy the code

9. The test

Distributed transaction is successful, to simulate normal orders, inventory localhost: 9091 / order/placeOrderTcc/commit distributed transaction failure, simulation order success, buckle inventory failure, The final rollback localhost: 9091 / order/placeOrderTcc/rollbackCopy the code