一、问题描述
需求:
实现任意两个账户间的转账操作,并对每次转账操作在数据库进行留痕,即记录日志。
预期效果:
无论转账操作是否成功,均进行转账操作的日志留痕。
关键思路:
日志的记录与转账操作隶属同一个事务,它们是同成功同失败的,但是我们希望即使转账操作失败,日志依然会被添加到数据库,也就是说存日志事务应该独立于转账事务,解决办法就是我们给业务层日志类单独添加事务,并设置属性,@Transactional(propagation = Propagation.REQUIRES_NEW)
分析:
① 基于转账操作案例添加日志模块,实现数据库中记录日志;
② 业务层转账操作,调用加钱、减钱方法;
③ 转账成功与失败所对应的日志内容应该是不同的,这里我使用 AOP 来给转账类添加新的功能;
④ MyAdvice 里定义两个通知,@AfterReturning 用于写转账类中的方法正常执行完毕后的操作,即调用业务层的日志类方法,@AfterThrowing 用于写转账类中的方法执行异常后的操作,先将 money 修改为 0 作为异常标志,然后也是调用业务层的日志类方法;
⑤ 业务层的日志类方法收到传来的参数,通过判断 money 是否为 0,进而做出不同的选择,即给数据层传递不同的参数,该参数就是日志内容;
⑥ 数据层接收到来自业务层的数据参数,进而对数据库实施操作,即插入操作;
⑦ 当前时间通过 now() 函数获取。
二、关键代码
1. 业务层转账类
package com.zxe.service.impl;
import com.zxe.dao.AccountDao;
import com.zxe.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class AccountServiceImpl implements AccountService {
@Autowired
private AccountDao accountDao;
@Override
public void transfer(String outUname, String inUname, int money) {
accountDao.outMoney(outUname, money);
int i = 1/0;
accountDao.inMoney(inUname, money);
}
}
2. 业务层日志类
package com.zxe.service.impl;
import com.zxe.dao.LogDao;
import com.zxe.service.LogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class LogServiceImpl implements LogService {
@Autowired
private LogDao logDao;
@Override
public void log(String outUname, String inUname, int money) {
if (money == 0) {
logDao.log(outUname + "向" + inUname + "的转账操作失败");
} else {
logDao.log(outUname + "向" + inUname + "转账" + money + "元人民币");
}
}
}
3. 数据层转账类
package com.zxe.dao;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Update;
public interface AccountDao {
@Update("update t_account set money = money + #{money} where uname = #{inUname}")
public void inMoney(@Param("inUname") String inUname, @Param("money") int money);
@Update("update t_account set money = money - #{money} where uname = #{outUname}")
public void outMoney(@Param("outUname") String outUname, @Param("money") int money);
}
4. 数据层日志类
package com.zxe.dao;
import org.apache.ibatis.annotations.Insert;
public interface LogDao {
@Insert("insert into t_log(info, createDate) value(#{info}, now())")
public void log(String info);
}
5. AOP 通知类
@Pointcut("execution(void com.zxe.service.AccountService.transfer(*, *, *))")
private void Pt() {
}
@Autowired
private LogService logService;
@AfterReturning("Pt()")
public void normal(JoinPoint jp) {
Object[] args = jp.getArgs();
logService.log((String)args[0], (String)args[1], (int)args[2]);
}
@AfterThrowing("Pt()")
public void abnormal(JoinPoint jp) {
Object[] args = jp.getArgs();
logService.log((String)args[0], (String)args[1], 0);
}
三、相关截图