当前位置:网站首页>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 !!!)
边栏推荐
- 【LGR-109】洛谷 5 月月赛 II & Windy Round 6
- yolov5 tensorrt加速
- Compilation et connexion de shader dans games202 - webgl (comprendre la direction)
- Delete subsequence < daily question >
- Quelques conseils communs sur l'inspecteur de l'unit é, généralement pour les extensions d'éditeur ou d'autres
- [FreeRTOS interrupt experiment]
- 内核判断i2c地址上是否挂载外设
- Three.js学习-光照和阴影(了解向)
- RT thread analysis - object container implementation and function
- 2021robocom robot developer competition (Preliminary)
猜你喜欢
[classic example] binary tree recursive structure classic topic collection @ binary tree
【LGR-109】洛谷 5 月月赛 II & Windy Round 6
Crazy God said redis notes
The IPO of mesk Electronics was terminated: Henan assets, which was once intended to raise 800 million yuan, was a shareholder
Postman pre script - global variables and environment variables
RTP gb28181 document testing tool
Postman管理测试用例
Sqlserver query results are not displayed in tabular form. How to modify them
Flink kakfa data read and write to Hudi
Class inheritance in yyds dry inventory C
随机推荐
Selection sort
RT thread analysis - object container implementation and function
Postman前置脚本-全局变量和环境变量
行业专网对比公网,优势在哪儿?能满足什么特定要求?
idea一键导包
也算是學習中的小總結
MPLS experiment
Request (request object) and response (response object)
Leetcode dynamic planning day 16
ISP learning (2)
Ora-01779: the column corresponding to the non key value saving table cannot be modified
[05-1, 05-02, 05-03] network protocol
最高法院,离婚案件判决标准
Quick sort
Realize a binary read-write address book
图论的扩展
Postman manage test cases
[数学建模] 微分方程--捕鱼业的持续发展
Fuzzy -- basic application method of AFL
Nestjs配置文件上传, 配置中间件以及管道的使用