spring---->Spring事务与ApplicationEventPublisher
2023-09-27 14:20:11 时间
Spring事务与ApplicationEventPublisher
@Transactional
public void handle() {
var account = Account.builder()
.username("huhx")
.password("pass")
.build();
accountRepository.save(account);
publisher.publishEvent(new AccountEvent("huhx"));
var account2 = Account.builder()
.username("huhx2")
.password("pass2")
.build();
accountRepository.save(account2);
}
@Component
@RequiredArgsConstructor
public class AccountEventHandler {
private final BookService bookService;
@EventListener(AccountEvent.class)
public void onAccountEvent(AccountEvent event) {
bookService.save(new BookRequest(event.username()));
throw new RuntimeException();
}
}
// 1. No books saved, no account saved
// 2. add @Transactional on onAccountEvent, No books saved, no account saved
// 3. add @Async on onAccountEvent, two accounts saved, one book saved
// 4. add @Async and @Transactional on onAccountEvent, only two accounts saved
// 5. execute in Thread and with @Transactional, two accounts saved, one book saved(这里加不加@Transactional,没区别)
@Transactional
@EventListener(AccountEvent.class)
public void handle(AccountEvent event) {
new Thread(() -> {
bookService.save(new BookRequest(event.username()));
throw new RuntimeException();
}).start();
}
// 6. change the eventHandle code as following, no accounts saved, only one book saved(这里加不加@Transactional,没区别)
@Transactional
@EventListener(AccountEvent.class)
public void handle(AccountEvent event) {
new Thread(() -> bookService.save(new BookRequest(event.username()))).start();
bookService.save(new BookRequest(event.username()));
throw new RuntimeException();
}
默认情况下,ApplicationEventPublisher的publishEvent方法是同步的
相关文章
- 开涛spring3(9.1) - Spring的事务 之 9.1 数据库事务概述
- Spring MVC系列之Hello World(SpringBoot)(六)
- 8 -- 深入使用Spring -- 6...1 Spring支持的事务策略
- Spring事务在单元测试中的应用
- [转]Spring事务嵌套引发的血案---Transaction rolled back because it has been marked as rollback-only
- spring boot 打jar包分离lib和resources
- [Java][Spring]Spring事务不起作用 问题汇总
- 深入分析Spring事务和底层原理
- spring事务传播机制
- 使用Ocelot、IdentityServer4、Spring Cloud Eureka搭建微服务网关:Step by Step(二)
- Spring Boot 整合Shiro 最新 最全面(Mybatis版本)
- 【Spring源码】Spring事务原理
- 清除控制台中Spring、SpringBoot、MyBatis-Plus的输出信息
- 通过eclipse配置Spring MVC项目
- 2015第24周三Spring事务3
- Spring Boot @EnableAutoConfiguration和 @Configuration的区别
- Spring之事务操作(配置文件)
- Spring对事务的支持及数据库事务
- Spring中@Import注解详细讲解及示例
- Spring事务超时时间可能存在的错误认识
- spring boot 2 + shiro 实现简单的身份验证例子
- 使用Spring Boot Actuator、Jolokia和Grafana实现准实时监控--转