Skip to content

Commit 68be00a

Browse files
committed
SpringBoot 2.0集成Atomikos实现多数据源及分布式事务的应用
1 parent ca97434 commit 68be00a

File tree

23 files changed

+1714
-0
lines changed

23 files changed

+1714
-0
lines changed

SpringBoot-JTA-Atomikos/.gitignore

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
.gradle
2+
/build/
3+
!gradle/wrapper/gradle-wrapper.jar
4+
5+
### STS ###
6+
.apt_generated
7+
.classpath
8+
.factorypath
9+
.project
10+
.settings
11+
.springBeans
12+
.sts4-cache
13+
14+
### IntelliJ IDEA ###
15+
.idea
16+
*.iws
17+
*.iml
18+
*.ipr
19+
/out/
20+
21+
### NetBeans ###
22+
/nbproject/private/
23+
/nbbuild/
24+
/dist/
25+
/nbdist/
26+
/.nb-gradle/

SpringBoot-JTA-Atomikos/README.md

Lines changed: 308 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,308 @@
1+
## SpringBoot2.X 集成Atomikos、Druid 实现多数据源及对分布式事务的应用
2+
3+
### 使用JTA处理分布式事务
4+
Spring Boot通过Atomkos或Bitronix的内嵌事务管理器支持跨多个XA资源的分布式JTA事务,当部署到恰当的J2EE应用服务器时也会支持JTA事务。
5+
6+
当发现JTA环境时,Spring Boot将使用Spring的 JtaTransactionManager 来管理事务。自动配置的JMS,DataSource和JPA beans将被升级以支持XA事务。可以使用标准的Spring idioms,比如 @Transactional ,来参与到一个分布式事务中。如果处于JTA环境,但仍想使用本地事务,你可以将 spring.jta.enabled 属性设置为 false 来禁用JTA自动配置功能。
7+
8+
> 常用的事务管理器有:Atomikos、Bitronix、Narayana。
9+
本文主要围绕Atomikos展开,另外的常用事务管理器可执行搜索了解。
10+
11+
### Atomikos简介
12+
Atomikos是一种流行的开源事务管理器,可以嵌入到Spring Boot应用程序中,你可以使用spring-boot-starter-jta-atomikos启动器来拉取适当的Atomikos库,Spring Boot可以自动配置Atomikos,并确保将适当的依赖设置应用到你的Spring bean中,以实现正确的启动和关闭顺序。
13+
14+
默认情况下,Atomikos事务日志被写入应用程序的主目录中的transaction-logs目录(应用程序jar文件所在的目录),你可以通过在application.properties文件中设置spring.jta.log-dir来定制这个目录的位置,从spring.jta.atomikos.properties开始的属性还可以用于定制Atomikos UserTransactionServiceImp,
15+
请参阅 [AtomikosProperties Javadoc](https://docs.spring.io/spring-boot/docs/2.0.4.RELEASE/api/org/springframework/boot/jta/atomikos/AtomikosProperties.html) 获取完整的详细信息。
16+
17+
> 为了确保多个事务管理器可以安全地协调相同的资源管理器,每个Atomikos实例必须配置唯一的ID,默认情况下,这个ID是Atomikos运行的机器的IP地址。为了确保生产中具有唯一性,你应该为应用程序的每个实例配置spring.jta.transaction-manager-id属性的不同值。
18+
19+
### 与SpringBoot集成
20+
SpringBoot默认提供了配置依赖,可直接导入jar包。
21+
```
22+
compile group: 'org.springframework.boot', name: 'spring-boot-starter-jta-atomikos', version: '2.0.4.RELEASE'
23+
compile group: 'com.alibaba', name: 'druid', version: '1.1.10'
24+
compile group: 'mysql', name: 'mysql-connector-java', version: '5.1.46'
25+
compile group: 'org.mybatis.spring.boot', name: 'mybatis-spring-boot-starter', version: '1.3.2'
26+
testCompile group: 'org.springframework.boot', name: 'spring-boot-starter-test', version: '2.0.4.RELEASE'
27+
```
28+
### 配置多数据源
29+
配置atomikos事务管理器,并配置druid作为数据源并且进行监控
30+
注入数据源使用使用的是com.atomikos.jdbc.AtomikosDataSourceBean,所以参照此类,可以制定以下配置,再使用
31+
@ConfigurationProperties注解根据前缀将配置注入该datasource,省取繁琐的设置配置。
32+
```properties
33+
##Spring表数据库配置
34+
spring.jta.atomikos.datasource.spring.max-pool-size=25
35+
spring.jta.atomikos.datasource.spring.min-pool-size=3
36+
spring.jta.atomikos.datasource.spring.max-lifetime=20000
37+
spring.jta.atomikos.datasource.spring.borrow-connection-timeout=10000
38+
spring.jta.atomikos.datasource.spring.unique-resource-name=spring
39+
spring.jta.atomikos.datasource.spring.xa-properties.url=jdbc:mysql://127.0.0.1:3306/spring?useUnicode=true&characterEncoding=UTF-8&useSSL=true&serverTimezone=UTC
40+
spring.jta.atomikos.datasource.spring.xa-properties.username=root
41+
spring.jta.atomikos.datasource.spring.xa-properties.password=root
42+
spring.jta.atomikos.datasource.spring.xa-properties.driverClassName=com.mysql.jdbc.Driver
43+
# 初始化大小,最小,最大
44+
spring.jta.atomikos.datasource.spring.xa-properties.initialSize=10
45+
spring.jta.atomikos.datasource.spring.xa-properties.minIdle=20
46+
spring.jta.atomikos.datasource.spring.xa-properties.maxActive=100
47+
## 配置获取连接等待超时的时间
48+
spring.jta.atomikos.datasource.spring.xa-properties.maxWait=60000
49+
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
50+
spring.jta.atomikos.datasource.spring.xa-properties.timeBetweenEvictionRunsMillis=60000
51+
# 配置一个连接在池中最小生存的时间,单位是毫秒
52+
spring.jta.atomikos.datasource.spring.xa-properties.minEvictableIdleTimeMillis=300000
53+
spring.jta.atomikos.datasource.spring.xa-properties.testWhileIdle=true
54+
spring.jta.atomikos.datasource.spring.xa-properties.testOnBorrow=false
55+
spring.jta.atomikos.datasource.spring.xa-properties.testOnReturn=false
56+
# 打开PSCache,并且指定每个连接上PSCache的大小
57+
spring.jta.atomikos.datasource.spring.xa-properties.poolPreparedStatements=true
58+
spring.jta.atomikos.datasource.spring.xa-properties.maxPoolPreparedStatementPerConnectionSize=20
59+
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
60+
spring.jta.atomikos.datasource.spring.xa-properties.filters=stat,slf4j,wall
61+
spring.jta.atomikos.datasource.spring.xa-data-source-class-name=com.alibaba.druid.pool.xa.DruidXADataSource
62+
63+
#------------------------------ 分隔符-------------------------------------
64+
##test表数据库配置
65+
spring.jta.atomikos.datasource.test.max-pool-size=25
66+
spring.jta.atomikos.datasource.test.min-pool-size=3
67+
spring.jta.atomikos.datasource.test.max-lifetime=20000
68+
spring.jta.atomikos.datasource.test.borrow-connection-timeout=10000
69+
spring.jta.atomikos.datasource.test.unique-resource-name=test
70+
spring.jta.atomikos.datasource.test.xa-properties.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=UTF-8&useSSL=true&serverTimezone=UTC
71+
spring.jta.atomikos.datasource.test.xa-properties.username=root
72+
spring.jta.atomikos.datasource.test.xa-properties.password=root
73+
spring.jta.atomikos.datasource.test.xa-properties.driverClassName=com.mysql.jdbc.Driver
74+
spring.jta.atomikos.datasource.test.xa-properties.initialSize=10
75+
spring.jta.atomikos.datasource.test.xa-properties.minIdle=20
76+
spring.jta.atomikos.datasource.test.xa-properties.maxActive=100
77+
spring.jta.atomikos.datasource.test.xa-properties.maxWait=60000
78+
spring.jta.atomikos.datasource.test.xa-properties.timeBetweenEvictionRunsMillis=60000
79+
spring.jta.atomikos.datasource.test.xa-properties.minEvictableIdleTimeMillis=300000
80+
spring.jta.atomikos.datasource.test.xa-properties.testWhileIdle=true
81+
spring.jta.atomikos.datasource.test.xa-properties.testOnBorrow=false
82+
spring.jta.atomikos.datasource.test.xa-properties.testOnReturn=false
83+
spring.jta.atomikos.datasource.test.xa-properties.poolPreparedStatements=true
84+
spring.jta.atomikos.datasource.test.xa-properties.maxPoolPreparedStatementPerConnectionSize=20
85+
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
86+
spring.jta.atomikos.datasource.test.xa-properties.filters=stat,slf4j,wall
87+
spring.jta.atomikos.datasource.test.xa-data-source-class-name=com.alibaba.druid.pool.xa.DruidXADataSource
88+
```
89+
接着将配置注入数据源,并且设置durid监控中心:
90+
```java
91+
@Configuration
92+
@EnableConfigurationProperties
93+
@EnableTransactionManagement(proxyTargetClass = true)
94+
public class MybatisConfiguration {
95+
/**
96+
* spring数据库配置前缀.
97+
*/
98+
final static String SPRING_PREFIX = "spring.jta.atomikos.datasource.spring";
99+
/**
100+
* test数据库配置前缀.
101+
*/
102+
final static String TEST_PREFIX = "spring.jta.atomikos.datasource.test";
103+
104+
/**
105+
* The constant logger.
106+
*/
107+
final static Logger logger = LoggerFactory.getLogger(MybatisConfiguration.class);
108+
109+
/**
110+
* 配置druid显示监控统计信息
111+
* 开启Druid的监控平台 http://localhost:8080/druid
112+
*
113+
* @return servlet registration bean
114+
*/
115+
@Bean
116+
public ServletRegistrationBean druidServlet() {
117+
logger.info("Init Druid Servlet Configuration ");
118+
ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
119+
// IP白名单,不设默认都可以
120+
// servletRegistrationBean.addInitParameter("allow", "192.168.2.25,127.0.0.1");
121+
// IP黑名单(共同存在时,deny优先于allow)
122+
servletRegistrationBean.addInitParameter("deny", "192.168.1.100");
123+
//控制台管理用户
124+
servletRegistrationBean.addInitParameter("loginUsername", "root");
125+
servletRegistrationBean.addInitParameter("loginPassword", "dashuai");
126+
//是否能够重置数据 禁用HTML页面上的“Reset All”功能
127+
servletRegistrationBean.addInitParameter("resetEnable", "false");
128+
return servletRegistrationBean;
129+
}
130+
131+
/**
132+
* 注册一个filterRegistrationBean
133+
*
134+
* @return filter registration bean
135+
*/
136+
@Bean
137+
public FilterRegistrationBean filterRegistrationBean() {
138+
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
139+
//添加过滤规则
140+
filterRegistrationBean.addUrlPatterns("/*");
141+
//添加不需要忽略的格式信息
142+
filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
143+
return filterRegistrationBean;
144+
}
145+
146+
/**
147+
* 配置Spring数据库的数据源
148+
*
149+
* @return the data source
150+
*/
151+
@Bean(name = "SpringDataSource")
152+
@ConfigurationProperties(prefix = SPRING_PREFIX) // application.properties中对应属性的前缀
153+
public DataSource springDataSource() {
154+
return new AtomikosDataSourceBean();
155+
}
156+
157+
/**
158+
* 配置Test数据库的数据源
159+
*
160+
* @return the data source
161+
*/
162+
@Bean(name = "TestDataSource")
163+
@ConfigurationProperties(prefix = TEST_PREFIX) // application.properties中对应属性的前缀
164+
public DataSource testDataSource() {
165+
return new AtomikosDataSourceBean();
166+
}
167+
}
168+
```
169+
再分别对每个数据源进行sessionfactory的配置:
170+
```java
171+
@Configuration
172+
@MapperScan(basePackages = {"com.dashuai.learning.jta.mapper.spring"}, sqlSessionFactoryRef = "springSqlSessionFactory")
173+
public class SpringDataSourceConfiguration {
174+
/**
175+
* The constant MAPPER_XML_LOCATION.
176+
*/
177+
public static final String MAPPER_XML_LOCATION = "classpath:mapper/spring/*.xml";
178+
179+
/**
180+
* The Open plat form data source.
181+
*/
182+
@Autowired
183+
@Qualifier("SpringDataSource")
184+
DataSource springDataSource;
185+
186+
/**
187+
* 配置Sql Session模板
188+
*
189+
* @return the sql session template
190+
* @throws Exception the exception
191+
*/
192+
@Bean
193+
public SqlSessionTemplate springSqlSessionTemplate() throws Exception {
194+
return new SqlSessionTemplate(springSqlSessionFactory());
195+
}
196+
197+
/**
198+
* 配置SQL Session工厂
199+
*
200+
* @return the sql session factory
201+
* @throws Exception the exception
202+
*/
203+
@Bean
204+
public SqlSessionFactory springSqlSessionFactory() throws Exception {
205+
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
206+
factoryBean.setDataSource(springDataSource);
207+
//指定XML文件路径
208+
factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(MAPPER_XML_LOCATION));
209+
return factoryBean.getObject();
210+
}
211+
}
212+
```
213+
Test数据源与Spring数据源大同小异,详情可查看源码。
214+
配置到达这里就完成了。再写一个测试用例,测试多数据源和事务效果:
215+
```java
216+
@RunWith(SpringRunner.class)
217+
@SpringBootTest
218+
public class JtaApplicationTests {
219+
220+
@Autowired
221+
UserService userService;
222+
@Autowired
223+
PeopleService peopleService;
224+
225+
@Test
226+
@Transactional
227+
public void contextLoads() {
228+
User user=new User();
229+
user.setUserName("你妹哦");
230+
user.setPassword("我去");
231+
user.setAge(20);
232+
userService.insertUser(user);
233+
People people = new People();
234+
people.setName("你大爺的");
235+
people.setAge(50);
236+
people.setSex("");
237+
peopleService.insertPeople(people);
238+
}
239+
}
240+
```
241+
由于是测试用例,默认@Transactional在全部成功执行完成会回滚,经测试没问题。
242+
![](https://ws1.sinaimg.cn/large/006mOQRagy1fzas8yi4ezj319p08habz.jpg)
243+
再写一个接口对两个表进行添加操作,并且其中一条语句执行失败,查看回滚效果:
244+
```java
245+
@Override
246+
@Transactional
247+
public Boolean insertUserAndPeople(User user, People people) throws RuntimeException {
248+
peopleMapper.insert(people);
249+
try {
250+
userMapper.insertSelective(user);
251+
} catch (Exception e) {
252+
throw new RuntimeException("抛出runtime异常,导致回滚数据");
253+
}
254+
return true;
255+
}
256+
```
257+
```java
258+
@PostMapping(value = "/insertPeopleAndUser", produces = "application/json;charset=UTF-8")
259+
@ApiOperation(value = "添加两个表", notes = "测试分布式事务", response = ApiResult.class)
260+
@ApiImplicitParams({
261+
@ApiImplicitParam(name = "peopleName", value = "人名", required = true, dataType = "String"),
262+
@ApiImplicitParam(name = "userName", value = "用户信息", required = true, dataType = "String")
263+
})
264+
public ApiResult insertPeopleAndUser(String peopleName,String userName) throws Exception {
265+
User user=new User();
266+
user.setUserName(userName);
267+
user.setPassword("15251251");
268+
user.setAge(22);
269+
People people = new People();
270+
people.setName(peopleName);
271+
people.setAge(20);
272+
people.setSex("");
273+
Boolean isSuccess = peopleService.insertUserAndPeople(user, people);
274+
if (isSuccess) {
275+
return ApiResult.prepare().success("同时添加两表成功!");
276+
}
277+
return ApiResult.prepare().error(JSONParseUtils.object2JsonString(people), 500, "添加失败,全部回滚");
278+
}
279+
```
280+
由于User表的name字段设置了唯一,所以只需插入重复即会报错。
281+
282+
> 注意,如果@Tranactional失效,可以思考以下问题:
283+
1.mysql是否使用的是innodb;
284+
2.Spring AOP只在抛出RuntimeException时才回滚,就是需要在捕获异常的最后加上throw new RuntimeException;
285+
3.尝试手动回滚。给注解加上参数如:@Transactional(rollbackFor=Exception.class)
286+
287+
分别向spring库里的user表和test库里的tet表插入一条数据
288+
![](https://ws1.sinaimg.cn/large/006mOQRagy1fzarp6ks5hj308v03sglk.jpg)
289+
![](https://ws1.sinaimg.cn/large/006mOQRagy1fzarqircf9j30ez03ajre.jpg)
290+
接着,返回接口添加user表已有的name,触发异常,查看回滚效果。
291+
![](https://ws1.sinaimg.cn/large/006mOQRagy1fzart26t4gj31a10p740s.jpg)
292+
出现唯一索引异常
293+
![](https://ws1.sinaimg.cn/large/006mOQRagy1fzarskw0k1j311s03y74y.jpg)
294+
查看表插入情况:
295+
![](https://ws1.sinaimg.cn/large/006mOQRagy1fzaru8ip89j30f4042dfv.jpg)
296+
可以看到,people表并没有插入数据,也就是当出现异常时,全部数据都回滚了。
297+
298+
> 学习之路,本就如同逆流而上,不进即退。加油!
299+
300+
本例子的源码已上传至github:
301+
https://github.com/liaozihong/SpringBoot-Learning/tree/master/SpringBoot-JTA-Atomikos.git
302+
303+
参考链接:
304+
[Spring boot atomikos 配置好后 @Transactional 注解不生效](https://blog.csdn.net/qq_32447301/article/details/81235582)
305+
[Spring Boot(二三) - 使用JTA处理分布式事务](https://www.hifreud.com/2017/07/12/spring-boot-23-jta-handle-distribute-transaction/#%E4%BD%BF%E7%94%A8jta%E5%A4%84%E7%90%86%E5%88%86%E5%B8%83%E5%BC%8F%E4%BA%8B%E5%8A%A1)
306+
307+
308+
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
2+
dependencies {
3+
compile project(':SpringBoot-Utils')
4+
compile group: 'org.springframework.boot', name: 'spring-boot-starter-jta-atomikos', version: '2.0.4.RELEASE'
5+
compile group: 'com.alibaba', name: 'druid', version: '1.1.10'
6+
compile group: 'mysql', name: 'mysql-connector-java', version: '5.1.46'
7+
compile group: 'org.mybatis.spring.boot', name: 'mybatis-spring-boot-starter', version: '1.3.2'
8+
testCompile group: 'org.springframework.boot', name: 'spring-boot-starter-test', version: '2.0.4.RELEASE'
9+
}
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package com.dashuai.learning.jta;
2+
3+
import org.springframework.boot.SpringApplication;
4+
import org.springframework.boot.autoconfigure.SpringBootApplication;
5+
6+
/**
7+
* Created in 2019.01.18
8+
*
9+
* @author Liaozihong
10+
*/
11+
@SpringBootApplication
12+
public class JtaApplication {
13+
14+
/**
15+
* The entry point of application.
16+
*
17+
* @param args the input arguments
18+
*/
19+
public static void main(String[] args) {
20+
SpringApplication.run(JtaApplication.class, args);
21+
}
22+
23+
}
24+

0 commit comments

Comments
 (0)