来自黑马程序员java面试题
案例准备:
数据库表数据如下,要实现的目标就是刘备曹操孙权向自己手下员工发工资转账,这是一个事务的典型应用场景。 数据库操作相关方法
@Override
public Account getAccountByName(String name) {
String querySql="select * from t_account where a_name=?";
BeanPropertyRowMapper<Account> beanPropertyRowMapper = new BeanPropertyRowMapper<>(Account.class);
return jdbcTemplate.queryForObject(querySql, beanPropertyRowMapper, name);
}
@Override
public int updateAccount(Account account) {
String updateSql="update t_account set a_balance=? where a_id=?";
return jdbcTemplate.update(updateSql, account.getaBalance(), account.getaId());
}
@Override
public void transfer(String sourceName, String objectName, double cash) {
Account A = getAccountByName(sourceName);
Account B = getAccountByName(objectName);
A.setaBalance(A.getaBalance()-cash);
B.setaBalance(B.getaBalance()+cash);
updateAccount(A);
updateAccount(B);
System.out.println("转账成功");
}
一.抛出检查异常导致事务不能正确回滚
@Transactional
@Override
public void transfer(String sourceName, String objectName, double cash) throws FileNotFindException{
Account A = getAccountByName(sourceName);
Account B = getAccountByName(objectName);
A.setaBalance(A.getaBalance()-cash);
B.setaBalance(B.getaBalance()+cash);
updateAccount(A);
new FileInputStream("");
updateAccount(B);
System.out.println("转账成功");
}
-
原因:Spring 默认只会回滚非检查异常 -
解法:配置 rollbackFor 属性
@Transactional(rollbackFor = Exception.class)
二.业务方法内自己 try-catch 异常导致事务不能正确回滚
@Transactional
@Override
public void transfer(String sourceName, String objectName, double cash) {
try {
Account A = getAccountByName(sourceName);
Account B = getAccountByName(objectName);
A.setaBalance(A.getaBalance()-cash);
B.setaBalance(B.getaBalance()+cash);
updateAccount(A);
new FileInputStream("");
updateAccount(B);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
System.out.println("转账成功");
}
三.AOP 切面顺序导致导致事务不能正确回滚
@Aspect
@Component
public class LogAspect {
@Around(value = "execution(* tx.service.impl.AccountServiceImpl.transfer(..))")
public Object printLog(ProceedingJoinPoint proceedingJoinPoint){
System.out.println("记入日志");
try {
return proceedingJoinPoint.proceed();
}catch (Throwable e){
e.printStackTrace();
}
}
}
四.非 public 方法导致的事务失效
@Transactional
@Override
void transfer(String sourceName, String objectName, double cash) throws FileNotFindException{
Account A = getAccountByName(sourceName);
Account B = getAccountByName(objectName);
A.setaBalance(A.getaBalance()-cash);
B.setaBalance(B.getaBalance()+cash);
updateAccount(A);
new FileInputStream("");
updateAccount(B);
System.out.println("转账成功");
}
@Bean
public TransactionAttributeSource transactionAttributeSource() {
return new AnnotationTransactionAttributeSource(false);
}
五.父子容器导致的事务失效
package day04.tx.app.service;
@Service
public class Service5 {
@Autowired
private AccountMapper accountMapper;
@Transactional(rollbackFor = Exception.class)
public void transfer(int from, int to, int amount) throws FileNotFoundException {
int fromBalance = accountMapper.findBalanceBy(from);
if (fromBalance - amount >= 0) {
accountMapper.update(from, -1 * amount);
accountMapper.update(to, amount);
}
}
}
控制器类
package day04.tx.app.controller;
@Controller
public class AccountController {
@Autowired
public Service5 service;
public void transfer(int from, int to, int amount) throws FileNotFoundException {
service.transfer(from, to, amount);
}
}
App 配置类
@Configuration
@ComponentScan("day04.tx.app.service")
@EnableTransactionManagement
public class AppConfig {
}
Web 配置类
@Configuration
@ComponentScan("day04.tx.app")
public class WebConfig {
}
现在配置了父子容器,WebConfig 对应子容器,AppConfig 对应父容器,发现事务依然失效
六.调用本类方法导致传播行为失效
@Service
public class Service6 {
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public void foo() throws FileNotFoundException {
LoggerUtils.get().debug("foo");
bar();
}
@Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
public void bar() throws FileNotFoundException {
LoggerUtils.get().debug("bar");
}
}
解法1
@Service
public class Service6 {
@Autowired
private Service6 proxy;
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public void foo() throws FileNotFoundException {
LoggerUtils.get().debug("foo");
System.out.println(proxy.getClass());
proxy.bar();
}
@Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
public void bar() throws FileNotFoundException {
LoggerUtils.get().debug("bar");
}
}
解法2,还需要在 AppConfig 上添加 @EnableAspectJAutoProxy(exposeProxy = true)
@Service
public class Service6 {
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public void foo() throws FileNotFoundException {
LoggerUtils.get().debug("foo");
((Service6) AopContext.currentProxy()).bar();
}
@Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
public void bar() throws FileNotFoundException {
LoggerUtils.get().debug("bar");
}
}
七.@Transactional 没有保证原子行为
**
@Service
public class Service7 {
private static final Logger logger = LoggerFactory.getLogger(Service7.class);
@Autowired
private AccountMapper accountMapper;
@Transactional(rollbackFor = Exception.class)
public void transfer(int from, int to, int amount) {
int fromBalance = accountMapper.findBalanceBy(from);
logger.debug("更新前查询余额为: {}", fromBalance);
if (fromBalance - amount >= 0) {
accountMapper.update(from, -1 * amount);
accountMapper.update(to, amount);
}
}
public int findBalance(int accountNo) {
return accountMapper.findBalanceBy(accountNo);
}
}
上面的代码实际上是有 bug 的,假设 from 余额为 1000,两个线程都来转账 1000,可能会出现扣减为负数的情况(两个线程都查询出1000然后都去执行转账操作导致出现负数情况)
- 原因:事务的原子性仅涵盖 insert、update、delete、select … for update 语句,select 方法并不阻塞
- 如上图所示,红色线程和蓝色线程的查询都发生在扣减之前,都以为自己有足够的余额做扣减
八.@Transactional 方法导致的 synchronized 失效
针对上面的问题,能否在方法上加 synchronized 锁来解决呢?
@Service
public class Service7 {
private static final Logger logger = LoggerFactory.getLogger(Service7.class);
@Autowired
private AccountMapper accountMapper;
@Transactional(rollbackFor = Exception.class)
public synchronized void transfer(int from, int to, int amount) {
int fromBalance = accountMapper.findBalanceBy(from);
logger.debug("更新前查询余额为: {}", fromBalance);
if (fromBalance - amount >= 0) {
accountMapper.update(from, -1 * amount);
accountMapper.update(to, amount);
}
}
public int findBalance(int accountNo) {
return accountMapper.findBalanceBy(accountNo);
}
}
答案是不行,原因如下:
- synchronized 保证的仅是目标方法的原子性(因为实际调用过程是代理对象调用方法),环绕目标方法的还有 commit 等操作,它们并未处于 sync 块内
- 可以参考下图发现,蓝色线程的查询只要在红色线程提交之前执行,那么依然会查询到有 1000 足够余额来转账
|