一个事务下,抛出异常事务回滚,要在开启一个线程将数据持久到数据库

需求:阅读记录孩子不存在时,发送一条私信给用户,同一个用户私信不能重复发。

====阅读记录孩子不存在时给用户发私信表(kid_user_station_letter_when_child_not_exist_in_reading_record)
user_id - 用户ID
time - 时间

遇见的问题:同一个事物下,私信发送成功,但没有保存到数据库中。

原因:事务回滚

解决:在开启一个线程,保存数据

KidChildInfo childInfo = childInfoMapper.selectByPrimaryKey(childId);

if (childInfo == null) {
  sendChildNotExistLetterToUser(userId);
  throw new Exception(String.format("孩子不存在:用户ID=%d, 孩子ID=%d, 已经发送解决方案私信给该用户", userId, childId));
}

private void sendChildNotExistLetterToUser(int userId) {
        AsynTaskService.run(new Runnable() {
            @Override
            public void run() {
                int count = commonMapper.executeQueryInt(String.format("SELECT COUNT(*) FROM kid_user_station_letter_when_child_not_exist_in_reading_record WHERE user_id=%d AND time>DATE_ADD(NOW(),INTERVAL -1 DAY)", userId));
                if (count == 0) {
                    commonMapper.executeInsert(String.format("INSERT INTO kid_user_station_letter_when_child_not_exist_in_reading_record(user_id, time) VALUES(%d, NOW()) ON DUPLICATE KEY UPDATE time=NOW()", userId));
                    stationLetterService.sendMessage(124244, userId, ""/**~!{
        Hi, 我们发现你的账号,孩子信息出错了,会导致闪退。
        为保障能正常使用,请重新添加下孩子吧。                   
                }*/);
                }
            }
        });
    }
原文地址:https://www.cnblogs.com/halo623/p/13813591.html