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

边栏推荐
猜你喜欢

yolov5 tensorrt加速

Delete subsequence < daily question >

ISP学习(2)

The underlying structure of five data types in redis

【LGR-109】洛谷 5 月月赛 II & Windy Round 6

Golang -- TCP implements concurrency (server and client)

Zynq learning notes (3) - partial reconfiguration

RTP gb28181 document testing tool

从0到1建设智能灰度数据体系:以vivo游戏中心为例

Class inheritance in yyds dry inventory C
随机推荐
Summary of three log knowledge points of MySQL
DMA use of stm32
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
JS quick start (II)
Raspberry pie 3.5-inch white screen display connection
[classic example] binary tree recursive structure classic topic collection @ binary tree
Some common skills on unity inspector are generally used for editor extension or others
Three. JS learning - light and shadow (understanding)
Cve-2019-11043 (PHP Remote Code Execution Vulnerability)
Uva1592 Database
项目经理,你会画原型嘛?项目经理需要做产品设计了?
Quatre méthodes de redis pour dépanner les grandes clés sont nécessaires pour optimiser
Golang -- TCP implements concurrency (server and client)
On the solution of es8316's audio burst
[NOIP2009 普及组] 分数线划定
Vite configures the development environment and production environment
[FreeRTOS interrupt experiment]
Sorting out the knowledge points of multicast and broadcasting
Building intelligent gray-scale data system from 0 to 1: Taking vivo game center as an example
Idea one key guide package