当前位置:网站首页>Nacos - TC Construction of High available seata (02)
Nacos - TC Construction of High available seata (02)
2022-07-06 05:00:00 【Kjshuan】
Phase préparatoire(Prepare phase): Le gestionnaire de transaction envoie à chaque participantPrepareMessage,Chaque participant à la base de données effectue des transactions localement,Et écrire localementUndo/RedoLog,La transaction n'est pas engagée pour le moment. ( UndoUn journal est un enregistrement des données avant modification,Pour le ROLLBACK de la base de données, RedoUn journal est un enregistrement des données modifiées,Utilisé pour écrire après avoir engagé une transaction Selon les documents) Phase de soumission(commit phase): Si le gestionnaire de transaction reçoit un message d'échec d'exécution ou de temporisation d'un participant,Envoyer un ROLLBACK directement à chaque participant(Rollback)Message;Sinon,Envoyer une soumission(Commit)Message;Le participant effectue une opération de commit ou de ROLLBACK selon les instructions du gestionnaire de transaction,Et libérer les ressources de verrouillage utilisées dans la transaction.Attention!:Les ressources de verrouillage doivent être libérées à la dernière étape.
#Créer une base de données 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-plusGénération automatique
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(); // // Ouvrir la base de données de connexion 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); //Définir la configuration globale 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); //Définir le nom du paquet 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"); // Définir le mode clé primaire pour chaque classe gc.setIdType(IdType.AUTO); //Définir le type de date gc.setDateType(DateType.ONLY_DATE); ag.setPackageInfo(pc); //Définir la politique 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(); } }
Étape 1 importerpomDépendance
<dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <!-- //ImportermybaitisCore--> <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>
Configuration de l'étape 2remoteInterface
@FeignClient(value = "stockmodule",path = "stock") public interface StockFeignService { @GetMapping(value = "/deduct/{shopid}/{num}") public String deduct(@PathVariable("shopid")Integer shopid, @PathVariable("num") Integer num); }
Étape 3 configurer la classe d'entité (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; } #serviceInterface public interface OrdersService extends IService<Orders> { void ordHndler(Orders ord); } #serviceClasse d'implémentation d'interface @Service public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService { @Resource private StockFeignService stockFeignService; @Override @Transactional public void ordHndler(Orders ord){ // Déposer la commande à mydemo1De la base de donnéesordersDans le tableau 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"; } } #applicationConfigurer les annotations @SpringBootApplication @EnableFeignClients @MapperScan("com.kgc.mynacos02.ordermodule.mapper") public class OrderApplication { public static void main(String[] args) { SpringApplication.run(OrderApplication.class,args); } }
Commande de démarrage Et les stocks2Services!!!
postmanInterface d'appel à distance
Seata**Installation( Le plus petit Succès du paquet!!)
Préparez - vous.2- Oui.jarSac Mets - le.optSous la table des matières
cd /opt/ ls tar -zxf seata-server-1.3.0.tar.gz mv seata soft/seata cd soft/seata/conf vim file.conf #Modifier4Données mode="db" serverAddr Adresse propre Numéro de compte, mot de passe 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 #Modifiertype = "nacos" serverAddrVotre adresse Numéro de comptenacosMot de passenacos #Modifierconfig type = "nacos" Numéro de comptenacosMot de passenacos # Tout a changé 7- Oui. :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 Voici l'adresse réelle de la salle des machines Peut être remplacé parnanjing ##Groupe des transactions La coupure de courant dans la salle des machines hors site peut être commutée À un stade ultérieurclientUtilisé lors de l'appel seata.service.vgroup- mapping.projectA=Moi - même. #Modifier4Un endroit. service.vgroupMapping.nanjing=default store.db.url=jdbc:mysql://192.168.64.135:3306/ store.db.user=root store.db.password=3090_Comk #Enregistrer la sortie :wq cd nacos/ ls ll #Oui.config.txt Téléchargement de fichiers dans le Centre de configuration sh nacos-config.sh -h 192.168.64.135 -p 8848 -g SEATA_GROUP cd /opt/soft/seata/bin/ ls #Démarrageseata server ./seata-server.sh -p 9009 -n 1
Ouvrir le Navigateur!
192.168.64.135:8848/nacos
L'écran ci - dessus indique une installation réussie !!
1)DémarrageSeata serverFin,Seata serverUtilisernacosEn tant que centre de configuration et d'enregistrement( L'étape précédente est terminée ) 2)
Première étapeConfigurer la consolidation des microservicesseata
<dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-seata</artifactId> </dependency>
Deuxième étape: Chaque micro - service est ajouté à la base de données correspondante undo_logTableau
mysql -uroot -p3090_Cmok use mydemo; # Exécuter le tableau ci - dessous #==================================== 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; #Même chose.
Troisième étape:Modifierapplication.ymlConfiguration(2 Edgar. )
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
postmanTests(Besoin deserviceDans la classe de mise en œuvre Exception personnalisée)
Interrogation de la base de données( L'inventaire n'a pas diminué et a été reporté avec succès !!!)
边栏推荐
- 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
- 饼干(考试版)
- Flink kakfa data read and write to Hudi
- Crazy God said redis notes
- Quatre méthodes de redis pour dépanner les grandes clés sont nécessaires pour optimiser
- 你需要知道的 TCP 三次握手
- Sorting out the knowledge points of multicast and broadcasting
- [FreeRTOS interrupt experiment]
- 比尔·盖茨晒18岁个人简历,48年前期望年薪1.2万美元
- 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
猜你喜欢
麥斯克電子IPO被終止:曾擬募資8億 河南資產是股東
Idea one key guide package
Golang -- TCP implements concurrency (server and client)
SQL injection vulnerability (MSSQL injection)
[FreeRTOS interrupt experiment]
GAMES202-WebGL中shader的编译和连接(了解向)
JS quick start (II)
Postman assertion
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
Compilation and connection of shader in games202 webgl (learn from)
随机推荐
Oracle deletes duplicate data, leaving only one
Quatre méthodes de redis pour dépanner les grandes clés sont nécessaires pour optimiser
Codeforces Round #804 (Div. 2)
Bill Gates posted his 18-year-old resume and expected an annual salary of $12000 48 years ago
Request (request object) and response (response object)
Biscuits (examination version)
RT thread analysis - object container implementation and function
也算是学习中的小总结
Set detailed map + interview questions
关于es8316的音频爆破音的解决
团队协作出了问题,项目经理怎么办?
Summary of redis basic knowledge points
JS quick start (II)
Redis has four methods for checking big keys, which are necessary for optimization
Quelques conseils communs sur l'inspecteur de l'unit é, généralement pour les extensions d'éditeur ou d'autres
Postman管理测试用例
Luogu deep foundation part 1 Introduction to language Chapter 2 sequential structure programming
Postman Association
Delete subsequence < daily question >
Excellent PM must experience these three levels of transformation!