当前位置:网站首页>Nacos TC setup of highly available Seata (02)
Nacos TC setup of highly available Seata (02)
2022-07-06 05:00:00 【kjshuan】
Preparation stage (Prepare phase): The transaction manager sends... To each participant Prepare news , Each database participant performs transactions locally , And write the local Undo/Redo journal , The transaction is not committed at this time . ( Undo Log is to record the data before modification , For database rollback , Redo Log is to record the modified data , The number of writes after the transaction has been committed According to the document ) Submission phase (commit phase): If the transaction manager receives an execution failure or timeout message from the participant , Send a rollback directly to each participant (Rollback) news ; otherwise , Send submit (Commit) news ; The participant performs commit or rollback operations according to the instructions of the transaction manager , And release the lock resources used in transaction processing . Be careful : Lock resources must be released at the last stage .
# Create database create database mydemo1; use mydemo1; create table orders(id int primary key not null auto_increment,orderdate date,shopid int not null,buynum int not null);
mybaits-plus Automatic generation
package com.kgc.mynacos02.ordermodule; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.generator.AutoGenerator; import com.baomidou.mybatisplus.generator.config.DataSourceConfig; import com.baomidou.mybatisplus.generator.config.GlobalConfig; import com.baomidou.mybatisplus.generator.config.PackageConfig; import com.baomidou.mybatisplus.generator.config.StrategyConfig; import com.baomidou.mybatisplus.generator.config.rules.DateType; import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy; public class GeneratorCode { public static void main(String[] args) { AutoGenerator ag = new AutoGenerator(); // // Open connection database DataSourceConfig dsc = new DataSourceConfig(); dsc.setUrl("jdbc:mysql://192.168.64.135:3306/mydemo1"); dsc.setDriverName("com.mysql.jdbc.Driver"); dsc.setUsername("root"); dsc.setPassword("3090_Cmok"); ag.setDataSource(dsc); // Set global configuration GlobalConfig gc = new GlobalConfig(); gc.setOutputDir(System.getProperty("user.dir")+"/mynacos02-ordermodule/src/main/java"); gc.setAuthor("js"); gc.setFileOverride(true); gc.setOpen(false); gc.setMapperName("%sMapper");//OrderMapper gc.setXmlName("%sMapper");//OrderMapper.xml gc.setServiceName("%sService");//Service gc.setServiceImplName("%sServiceImpl"); gc.setControllerName("%sCtrl"); ag.setGlobalConfig(gc); // Set package name PackageConfig pc = new PackageConfig(); pc.setParent("com.kgc.mynacos02.ordermodule"); pc.setMapper("mapper"); pc.setEntity("domain"); pc.setController("controller"); pc.setService("services"); pc.setServiceImpl("services.impl"); // Set the primary key method of each class gc.setIdType(IdType.AUTO); // Set date type gc.setDateType(DateType.ONLY_DATE); ag.setPackageInfo(pc); // Set the strategy StrategyConfig sc = new StrategyConfig(); sc.setEntityLombokModel(true); sc.setRestControllerStyle(true); sc.setColumnNaming(NamingStrategy.underline_to_camel); sc.setNaming(NamingStrategy.underline_to_camel); ag.setStrategy(sc); ag.execute(); } }
The first step is to import pom rely on
<dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <!-- // Import mybaitis The core --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.4.2</version> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-generator</artifactId> <version>3.4.1</version> </dependency> <dependency> <groupId>org.apache.velocity</groupId> <artifactId>velocity</artifactId> <version>1.7</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.38</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.1.9</version> </dependency> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency> </dependencies>
The second step is configuration remote Interface
@FeignClient(value = "stockmodule",path = "stock") public interface StockFeignService { @GetMapping(value = "/deduct/{shopid}/{num}") public String deduct(@PathVariable("shopid")Integer shopid, @PathVariable("num") Integer num); }
Step 3: configure the entity class (domain service controller)
#domain @Data @Builder @EqualsAndHashCode(callSuper = false) public class Orders implements Serializable { private static final long serialVersionUID = 1L; @TableId(value = "id", type = IdType.AUTO) private Integer id; private Date orderdate; private Integer shopid; private Integer buynum; } #service Interface public interface OrdersService extends IService<Orders> { void ordHndler(Orders ord); } #service Interface implementation class @Service public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService { @Resource private StockFeignService stockFeignService; @Override @Transactional public void ordHndler(Orders ord){ // Store the order in mydemo1 Database orders In the table save(ord); stockFeignService.deduct(ord.getShopid(),ord.getBuynum()); } } #controller @RestController @RequestMapping("/orders") public class OrdersCtrl { @Resource private OrdersService os; @RequestMapping(value = "/addOrder",method = RequestMethod.GET) public String addOrder(@RequestParam("shopid") int shopid,@RequestParam("buynum") int buynum){ Orders ord = Orders.builder().orderdate(new Date()).shopid(shopid).buynum(buynum).build(); os.ordHndler(ord); return "SUCCESS"; } } #application Configuration comments @SpringBootApplication @EnableFeignClients @MapperScan("com.kgc.mynacos02.ordermodule.mapper") public class OrderApplication { public static void main(String[] args) { SpringApplication.run(OrderApplication.class,args); } }
Start order And inventory 2 A service !!!
postman Remote call interface
Seata** install ( The finest in history Package success !!)
Get ready 2 individual jar package Put it in opt Under the table of contents
cd /opt/ ls tar -zxf seata-server-1.3.0.tar.gz mv seata soft/seata cd soft/seata/conf vim file.conf # modify 4 Data mode="db" serverAddr Own address Account and password cd /opt/ mkdir sta mv seata-1.3.0.zip sta/ cd sta/ yum install -y unzip zip unzip seata-1.3.0.zip cd seata-1.3.0 ls mysql -uroot -p3090_Cmok create database seata; use seata; source /opt/sta/seata-1.3.0/script/server/db/mysql.sql exit; cd /opt/soft/seata/conf vim registry.conf # modify type = "nacos" serverAddr Your address account number nacos password nacos # modify config type = "nacos" account number nacos password nacos # A total of 7 individual :wq cd /opt ls cd sta/seata-1.3.0/script/config-center/ vim config.txt #service.vgroupMapping.my_test_tx_group=default #my_test_tx_group This is the real computer room address You can change to nanjing ## Transaction grouping Power failure in remote machine rooms can be switched In the later period client Use... When calling seata.service.vgroup- mapping.projectA= own # modify 4 A place to service.vgroupMapping.nanjing=default store.db.url=jdbc:mysql://192.168.64.135:3306/ store.db.user=root store.db.password=3090_Comk # Save and exit :wq cd nacos/ ls ll # take config.txt Upload the file to the configuration center sh nacos-config.sh -h 192.168.64.135 -p 8848 -g SEATA_GROUP cd /opt/soft/seata/bin/ ls # start-up seata server ./seata-server.sh -p 9009 -n 1
Open the browser !
192.168.64.135:8848/nacos
The appearance of the above interface indicates that the installation is successful !!
1) start-up Seata server End ,Seata server Use nacos As a configuration center and registry ( The previous step has been completed ) 2)
First step Configure microservice integration seata
<dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-seata</artifactId> </dependency>
The second step : Add undo_log surface
mysql -uroot -p3090_Cmok use mydemo; # Execute the following table #==================================== 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, PRIMARY KEY (`id`), UNIQUE KEY `ux_undo_log` (`xid`,`branch_id`) ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8; #==================================== use mydemo1; # Empathy
The third step : modify application.yml To configure (2 Add both sides )
server: port: 8003 spring: application: name: ordermodule datasource: druid: url: jdbc:mysql://192.168.64.135:3306/mydemo1?useSSL=false&serverTimezone=Asia/Shanghai&characterEncoding=utf-8&autoReconnect=true username: root password: 3090_Cmok initial-size: 3 max-active: 30 min-idle: 3 max-wait: 60000 time-between-eviction-runs-millis: 60000 min-evictable-idle-time-millis: 300000 validation-query: select 1 test-on-borrow: true test-while-idle: false test-on-return: false pool-prepared-statements: true max-pool-prepared-statement-per-connection-size: 30 filter: stat,wall connection-properties: druid.stat.mergeSql=true;druid.stat.slowSq1Millis=500 use-global-data-source-stat: true cloud: nacos: discovery: server-addr: 192.168.64.135:8848 username: nacos password: nacos namespace: public alibaba: seata: tx-service-group: nanjing mybatis-plus: mapper-locations: mapper/*.xml seata: registry: type: nacos nacos: server-addr: 192.168.64.135:8848 username: nacos password: nacos application: seata-server config: type: nacos nacos: server-addr: 192.168.64.135:8848 username: nacos password: nacos group: SEATA_GROUP namespace: public
postman test ( Need to be in service In the implementation class Custom exception )
Query the database ( Rollback succeeded without inventory reduction !!!)
边栏推荐
- Embedded development program framework
- Postman断言
- [FreeRTOS interrupt experiment]
- The video in win10 computer system does not display thumbnails
- [mathematical modeling] differential equation -- sustainable development of fishing industry
- Weng Kai C language third week 3.1 punch in
- 【LGR-109】洛谷 5 月月赛 II & Windy Round 6
- Driver development - hellowdm driver
- 力扣(LeetCode)186. 翻转字符串里的单词 II(2022.07.05)
- Flody的应用
猜你喜欢
Distributed transaction solution
比尔·盖茨晒18岁个人简历,48年前期望年薪1.2万美元
RT thread analysis log system RT_ Kprintf analysis
麥斯克電子IPO被終止:曾擬募資8億 河南資產是股東
麦斯克电子IPO被终止:曾拟募资8亿 河南资产是股东
Postman关联
Uva1592 Database
Ad20 is set with through-hole direct connection copper sheet, and the bonding pad is cross connected
【LGR-109】洛谷 5 月月赛 II & Windy Round 6
What are the advantages of the industry private network over the public network? What specific requirements can be met?
随机推荐
JS quick start (II)
A little knowledge of CPU, disk and memory
[noip2009 popularization group] score line delimitation
Application of Flody
A blog to achieve embedded entry
Selection sort
Chip debugging of es8316 of imx8mp
Rce code and Command Execution Vulnerability
Fiddler installed the certificate, or prompted that the certificate is invalid
Crazy God said redis notes
The underlying structure of five data types in redis
优秀PM必须经历这3层蜕变!
The web project imported the MySQL driver jar package but failed to load it into the driver
麥斯克電子IPO被終止:曾擬募資8億 河南資產是股東
Ora-01779: the column corresponding to the non key value saving table cannot be modified
Redis 排查大 key 的4種方法,優化必備
Postman断言
Yolov5 tensorrt acceleration
[lgr-109] Luogu may race II & windy round 6
Driver development - hellowdm driver