实现用例分析
上篇基于Kafka消息驱动最终一致事务(一)介绍BASE的理论,接着我们引入一个实例看如何实现BASE,我们会用图7显示的算法实现BASE。
首先介绍使用技术栈
JDK:1.8
Spring:spring-boot,spring-data-jpa
数据库:Mysql
消息服务器:Kafka
数据表
用户库user创建用户表user,更新应用表updates_applied
CREATE TABLE `user` (
`id`INT(11) NOT NULLAUTO_INCREMENT,
`name`VARCHAR(50) NOT NULL,
`amt_sold`INT(11) NOT NULL DEFAULT '0',
`amt_bought`INT(11) NOT NULL DEFAULT '0',PRIMARY KEY(`id`)
);CREATE TABLE`updates_applied` (
`trans_id`INT(11) NOT NULL,
`balance`VARCHAR(50) NOT NULL,
`user_id` INT(11) NOT NULL);
交易库transaction创建交易库表transaction
CREATE TABLE `transaction` (
`xid`INT(11) NOT NULLAUTO_INCREMENT,
`seller_id`INT(11) NOT NULL,
`buyer_id`INT(11) NOT NULL,
`amount`INT(11) NOT NULL,PRIMARY KEY(`xid`)
);
配置两个数据源
package cn.birdstudio.user.domain;
import javax.sql.DataSource;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
@Configuration
@EnableJpaRepositories(basePackageClasses = User.class, entityManagerFactoryRef = "userEntityManagerFactory", transactionManagerRef = "userTransactionManager")
class UserDataSourceConfiguration {
@Bean
@ConfigurationProperties("app.datasource.user")
DataSourceProperties userDataSour