posts - 206,  comments - 26,  views - 17万
< 2025年2月 >
26 27 28 29 30 31 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 1
2 3 4 5 6 7 8

一、转账业务追加日志分析

实现任意两个账户间转账操作,并对每次转账操作在数据库进行留痕
即:A账户减钱,B账户加钱,数据库记录日志
无论转账操作是否成功,均进行转账操作的日志留痕

事务传播行为


二、事务传播行为


事务传播行为:事务协调员对事务管理员所携带事务的处理态度

 

 事务传播行为2

添加日志是一个新的事务;

事务传播行为:

 

三、转账日志案例

实现步骤:

第一步、在AccountServiceImpl中调用logService中添加日志的方法, 添加日志是一个新的事务。

复制代码
@Service
public class AccountServiceImpl implements AccountService {
    @Autowired
    private AccountDao accountDao;
 
    @Autowired
    private LogService logService;
 
    public void transfer(String out,String in ,Double money) {
        try{
            accountDao.outMoney(out,money);
            int i = 1/0;
            accountDao.inMoney(in,money);
        }finally {
            logService.log(out,in,money);
        }
    }
}
复制代码

 

 

 

第二步、在LogService的log()方法上设置事务的传播行为

public interface LogService {
    //propagation设置事务属性:传播行为设置为当前操作需要新事务
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    void log(String out, String in, Double money);
}

 

 

第三步、运行测试类,查看结果

复制代码
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfig.class)
public class AccountServiceTest {
    @Autowired
    private AccountService accountService;
 
    @Test
    public void testTransfer() throws IOException {
        accountService.transfer("Tom","Jerry",50D);
    }
}
复制代码

 


实现成功。

posted on   努力--坚持  阅读(11)  评论(0编辑  收藏  举报
(评论功能已被禁用)
相关博文:
阅读排行:
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
· 上周热点回顾(2.17-2.23)
点击右上角即可分享
微信分享提示