当前位置:网站首页>nacos-高可用seata之TC搭建(02)
nacos-高可用seata之TC搭建(02)
2022-07-06 05:00:00 【kjshuan】
准備階段(Prepare phase): 事務管理器給每個參與者發送Prepare消息,每個數據庫參與者在本地執行事務,並寫本地的Undo/Redo日志,此時事務沒有提交。 ( Undo日志是記錄修改前的數據,用於數據庫回滾, Redo日志是記錄修改後的數據,用於提交事務後寫入數 據文件) 提交階段(commit phase): 如果事務管理器收到了參與者的執行失敗或者超時消息時,直接給每個參與者發送回滾(Rollback)消息;否則,發送提交(Commit)消息;參與者根據事務管理器的指令執行提交或者回滾操作,並釋放事務處理過程中使用的鎖資源。注意:必須在最後階段釋放鎖資源。
#創建數據庫 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自動生成
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(); // //開啟連接數據庫 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); //設置全局配置 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); //設置包名 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"); //設置每個類的主鍵方式 gc.setIdType(IdType.AUTO); //設置日期類型 gc.setDateType(DateType.ONLY_DATE); ag.setPackageInfo(pc); //設置策略 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(); } }
第一步導入pom依賴
<dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <!-- //導入mybaitis核心--> <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>
第二步配置remote接口
@FeignClient(value = "stockmodule",path = "stock") public interface StockFeignService { @GetMapping(value = "/deduct/{shopid}/{num}") public String deduct(@PathVariable("shopid")Integer shopid, @PathVariable("num") Integer num); }
第三步配置實體類 (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接口 public interface OrdersService extends IService<Orders> { void ordHndler(Orders ord); } #service接口實現類 @Service public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService { @Resource private StockFeignService stockFeignService; @Override @Transactional public void ordHndler(Orders ord){ //把訂單存放到mydemo1數據庫的orders錶中 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配置注解 @SpringBootApplication @EnableFeignClients @MapperScan("com.kgc.mynacos02.ordermodule.mapper") public class OrderApplication { public static void main(String[] args) { SpringApplication.run(OrderApplication.class,args); } }
啟動訂單 和庫存2個服務!!!
postman遠程調用接口
Seata**安裝(史上最細 包成功!!)
准備一下2個jar包 放到opt目錄下
cd /opt/ ls tar -zxf seata-server-1.3.0.tar.gz mv seata soft/seata cd soft/seata/conf vim file.conf #修改4個數據 mode="db" serverAddr 自己的地址 賬號密碼 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 #修改type = "nacos" serverAddr你的地址 賬號nacos密碼nacos #修改config type = "nacos" 賬號nacos密碼nacos #一共改7個 :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這個為真實機房地址 可以改成nanjing ##事務分組 异地機房停電可以切換 在後期client調用時候使用 seata.service.vgroup- mapping.projectA=自己 #修改4個地方 service.vgroupMapping.nanjing=default store.db.url=jdbc:mysql://192.168.64.135:3306/ store.db.user=root store.db.password=3090_Comk #保存退出 :wq cd nacos/ ls ll #將config.txt文件上傳到配置中心 sh nacos-config.sh -h 192.168.64.135 -p 8848 -g SEATA_GROUP cd /opt/soft/seata/bin/ ls #啟動seata server ./seata-server.sh -p 9009 -n 1
打開瀏覽器!
192.168.64.135:8848/nacos
出現以上界面錶明安裝成功!!
1)啟動Seata server端,Seata server使用nacos作為配置中心和注册中心(上一步已完成) 2)
第一步配置微服務整合seata
<dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-seata</artifactId> </dependency>
第二步: 各微服務對應數據庫中添加undo_log錶
mysql -uroot -p3090_Cmok use mydemo; #執行下面建錶 #==================================== 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; #同理
第三步:修改application.yml配置(2邊都加)
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測試(需要在service實現類中 自定義异常)
查詢數據庫(庫存沒减回滾成功!!!)
边栏推荐
- [try to hack] John hash cracking tool
- Project manager, can you draw prototypes? Does the project manager need to do product design?
- [buuctf.reverse] 159_[watevrCTF 2019]Watshell
- Introduction of several RS485 isolated communication schemes
- 组播和广播的知识点梳理
- 麦斯克电子IPO被终止:曾拟募资8亿 河南资产是股东
- RTP GB28181 文件测试工具
- 【LGR-109】洛谷 5 月月赛 II & Windy Round 6
- 驱动开发——第一个HelloDDK
- [lgr-109] Luogu may race II & windy round 6
猜你喜欢
Delete subsequence < daily question >
麥斯克電子IPO被終止:曾擬募資8億 河南資產是股東
Three methods of Oracle two table Association update
Flody的应用
从0到1建设智能灰度数据体系:以vivo游戏中心为例
A blog to achieve embedded entry
比尔·盖茨晒18岁个人简历,48年前期望年薪1.2万美元
L'introduction en bourse de MSK Electronics a pris fin: 800 millions de RMB d'actifs de Henan étaient des actionnaires
Postman manage test cases
Leetcode dynamic planning day 16
随机推荐
Redis 排查大 key 的4种方法,优化必备
Building intelligent gray-scale data system from 0 to 1: Taking vivo game center as an example
Drive development - the first helloddk
[buuctf.reverse] 159_ [watevrCTF 2019]Watshell
Zynq learning notes (3) - partial reconfiguration
Upload nestjs configuration files, configure the use of middleware and pipelines
Microblogging hot search stock selection strategy
也算是学习中的小总结
也算是學習中的小總結
Excellent PM must experience these three levels of transformation!
Platformio create libopencm3 + FreeRTOS project
MySQL time processing
集合详解之 Map + 面试题
2021 RoboCom 世界机器人开发者大赛-本科组(复赛)
Ad20 is set with through-hole direct connection copper sheet, and the bonding pad is cross connected
Rce code and Command Execution Vulnerability
你需要知道的 TCP 三次握手
Pagoda configuration mongodb
[noip2008 improvement group] stupid monkey
树莓派3.5寸屏幕白屏显示连接