当前位置:网站首页>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 !!!)

边栏推荐
- Flink kakfa data read and write to Hudi
- The kernel determines whether peripherals are attached to the I2C address
- JS quick start (II)
- Fuzzy -- basic application method of AFL
- Biscuits (examination version)
- web工程导入了mysql驱动jar包却无法加载到驱动的问题
- 程序员在互联网行业的地位 | 每日趣闻
- Some common skills on unity inspector are generally used for editor extension or others
- A little knowledge of CPU, disk and memory
- What should the project manager do if there is something wrong with team collaboration?
猜你喜欢

Crazy God said redis notes

Vite configures the development environment and production environment

GAMES202-WebGL中shader的编译和连接(了解向)

Ora-01779: the column corresponding to the non key value saving table cannot be modified

idea一键导包

yolov5 tensorrt加速

The ECU of 21 Audi q5l 45tfsi brushes is upgraded to master special adjustment, and the horsepower is safely and stably increased to 305 horsepower

Introduction of several RS485 isolated communication schemes

Three methods of Oracle two table Association update

Rce code and Command Execution Vulnerability
随机推荐
Postman关联
Redis 排查大 key 的4種方法,優化必備
Bubble sort
Mongodb basic knowledge summary
[noip2009 popularization group] score line delimitation
驱动开发——HelloWDM驱动
SQL injection vulnerability (MSSQL injection)
acwing周赛58
The underlying structure of five data types in redis
麥斯克電子IPO被終止:曾擬募資8億 河南資產是股東
TCP three handshakes you need to know
GAMES202-WebGL中shader的编译和连接(了解向)
Hometown 20 years later (primary school exercises)
Platformio create libopencm3 + FreeRTOS project
L'introduction en bourse de MSK Electronics a pris fin: 800 millions de RMB d'actifs de Henan étaient des actionnaires
你需要知道的 TCP 三次握手
ISP learning (2)
Upload nestjs configuration files, configure the use of middleware and pipelines
Set detailed map + interview questions
最高法院,离婚案件判决标准