事务—【01】Spring事务管理介绍以及SpringBoot+

2020-01-11  本文已影响0人  苡仁ilss

前置知识

事务是什么?

事务的特性

并发事务的问题

  1. 脏读:脏读是指在一个事务处理过程里读取了另一个未提交的事务中的数据,针对对某一项数据
  2. 不可重复读:一个事务范围内多次查询却返回了不同的数据值,是由于在查询间隔,被另一个事务修改并提交了。
  3. 幻读:是指在事务执行过程中多次查询出来的数据数,不一致,比如通过where筛选第二次比第一次多几条别的事务新插入的数据,幻读针对的是一批数据整体

事务的隔离级别

Spring事务

1. 事务抽象

1.1 PlatformTransactionManager

public interface PlatformTransactionManager extends TransactionManager {
    TransactionStatus getTransaction(@Nullable TransactionDefinition definition)
            throws TransactionException;

    void commit(TransactionStatus status) throws TransactionException;

    void rollback(TransactionStatus status) throws TransactionException;

}

1.2 TransactionDefinition

事务传播机制,也就是在事务在多个方法的调用中是如何传递的;如:两个service的方法都是事务操作,一个事务方法调用另一个事务方法如何进行处理?


public interface TransactionDefinition {

    // 事务的传播机制
    // 如果调用方有事务则使用调用方的事务,如果不存在事务则创建一个事务
    int PROPAGATION_REQUIRED = 0;

    // 跟随调用方,如果调用方有 那就用,调用方没有那就不用
    int PROPAGATION_SUPPORTS = 1;

    // 调用方的方法必须运行在一个事务中,不存在事务则抛出异常
    int PROPAGATION_MANDATORY = 2;

    // 不管调用方是否有事务执行,自己都要起一个新事务。把原先的事务挂起,这个只在jta的事务管理器中起作用(事务是不支持嵌套的)
    int PROPAGATION_REQUIRES_NEW = 3;

    // 即使调用方有事务,我也要在非事务中执行,把原先的事务挂起
    int PROPAGATION_NOT_SUPPORTED = 4; 

    // 绝不在事务里面执行
    int PROPAGATION_NEVER = 5;

    // 嵌套事务(实际是不支持的,是利用存盘点来实现,把调用方之前执行的存盘点,然后类似于再开启一个事务执行,执行完毕后恢复存盘点,继续执行。JDBC3.0以上支持)
    int PROPAGATION_NESTED = 6;

    // 以下定义的是事务的隔离机制
    // 根据数据库的默认的隔离机制而定
    int ISOLATION_DEFAULT = -1;

    // 读未提交
    int ISOLATION_READ_UNCOMMITTED = 1;  // same as java.sql.Connection.TRANSACTION_READ_UNCOMMITTED;

    // 读已提交
    int ISOLATION_READ_COMMITTED = 2;  // same as java.sql.Connection.TRANSACTION_READ_COMMITTED;

    // 可重复读
    int ISOLATION_REPEATABLE_READ = 4;  // same as java.sql.Connection.TRANSACTION_REPEATABLE_READ;

    // 串行化
    int ISOLATION_SERIALIZABLE = 8;  // same as java.sql.Connection.TRANSACTION_SERIALIZABLE;


    // 默认超时时间,以数据库设定为准
    int TIMEOUT_DEFAULT = -1;

    // 获取事务的传播属性
    default int getPropagationBehavior() {
        return PROPAGATION_REQUIRED;
    }

    // 获取事务的隔离级别
    default int getIsolationLevel() {
        return ISOLATION_DEFAULT;
    }

    // 获取事务超时时间
    default int getTimeout() {
        return TIMEOUT_DEFAULT;
    }

    // 事务是否只读。
    default boolean isReadOnly() {
        return false;
    }

    // 获取事务的名称
    @Nullable
    default String getName() {
        return null;
    }

    // 返回一个默认事务定义
    static TransactionDefinition withDefaults() {
        return StaticTransactionDefinition.INSTANCE;
    }

}

1.3 TransactionStatus

// Savepoiont就是在Nested这种传播机制中提供保存点机制来实现嵌套事务,出错的时候可以选择恢复到保存点
public interface TransactionStatus extends TransactionExecution, SavepointManager, Flushable {
    // 是否有保存点
    boolean hasSavepoint();

    @Override
    void flush();
}
public interface TransactionExecution {
    // 是否是一个新事务
    boolean isNewTransaction();

    // 设置事务回滚
    void setRollbackOnly();
    
    // 事务是否回滚
    boolean isRollbackOnly();
    
    // 获取事务是否完成 
    boolean isCompleted();

}

2. PlatformTransactionManager常见的实现

3. Spring单数据源事务实际案例

3.1 环境说明:

3.2 实例代码

@Slf4j
@Service
public class AccountServiceImpl implements AccountService {
    @Autowired
    private AccountDAO accountDAO;
    @Autowired
    PlatformTransactionManager transactionManager;
    /**
     * 声明式事务
     * propagation = Propagation.REQUIRED (默认值就是REQUIRED) 如果调用方有事务就直接使用调用方的事务,如果没有就新建一个事务
     * transactionManager = "transactionManager" 也是默认值
     * isolation= Isolation.DEFAULT 隔离级别
     * 还有timeout等参数 可自行查看Transactional的源码 里面都有说明
     * @param sourceAccountId 源账户
     * @param targetAccountId 目标账户
     * @param amount 金额
     * @return 操作结果信息
     */
    @Override
    @Transactional(transactionManager = "transactionManager",propagation = Propagation.REQUIRED, rollbackFor = Exception.class, isolation= Isolation.DEFAULT)
    public String transferAnnotation(Long sourceAccountId, Long targetAccountId, BigDecimal amount) {
        AccountDO sourceAccountDO = accountDAO.selectByPrimaryKey(sourceAccountId);
        AccountDO targetAccountDO = accountDAO.selectByPrimaryKey(targetAccountId);
        if (null == sourceAccountDO || null == targetAccountDO) {
            return "转入或者转出账户不存在";
        }
        if (sourceAccountDO.getBalance().compareTo(amount) < 0) {
            return "转出账户余额不足";
        }
        sourceAccountDO.setBalance(sourceAccountDO.getBalance().subtract(amount));
        accountDAO.updateByPrimaryKeySelective(sourceAccountDO);
        // error("annotation error!");
        targetAccountDO.setBalance(targetAccountDO.getBalance().add(amount));
        accountDAO.updateByPrimaryKeySelective(targetAccountDO);
        return "转账成功!";
    }

    @Override
    public String transferCode(Long sourceAccountId, Long targetAccountId, BigDecimal amount) {
        TransactionDefinition transactionDefinition = new DefaultTransactionDefinition();
        // 获取事务 开始业务执行
        TransactionStatus transaction = transactionManager.getTransaction(transactionDefinition);
        try {
            AccountDO targetAccountDO = accountDAO.selectByPrimaryKey(targetAccountId);
            AccountDO sourceAccountDO = accountDAO.selectByPrimaryKey(sourceAccountId);
            if (null == sourceAccountDO || null == targetAccountDO) {
                return "转入或者转出账户不存在";
            }
            error("code error");
            if (sourceAccountDO.getBalance().compareTo(amount) < 0) {
                return "转出账户余额不足";
            }
            sourceAccountDO.setBalance(sourceAccountDO.getBalance().subtract(amount));
            targetAccountDO.setBalance(targetAccountDO.getBalance().add(amount));
            accountDAO.updateByPrimaryKeySelective(sourceAccountDO);
            accountDAO.updateByPrimaryKeySelective(sourceAccountDO);
            // 提交事务
            transactionManager.commit(transaction);
            return "转账成功!";
        } catch (Exception e) {
            log.error("转账发生错误,开始回滚,source: {}, target: {}, amount: {}, errMsg: {}",
                    sourceAccountId, targetAccountId, amount, e.getMessage());
            // 报错回滚
            transactionManager.rollback(transaction);
        }
        return "转账失败";
    }

    @Override
    public List<AccountDO> listAll() {
        return accountDAO.selectAll();
    }


    private static void error(String msg) {
        throw new RuntimeException(msg);
    }
}

3.3 Transactional注解实现事务


o.s.web.servlet.DispatcherServlet        : GET "/api/account/transfer/annotation?source=1&target=2&amount=123", parameters={masked}
s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to io.ilss.transaction.onedatasource.web.AccountController#transferAnnotation(Long, Long, String)
o.s.j.d.DataSourceTransactionManager     : Creating new transaction with name [io.ilss.transaction.onedatasource.service.impl.AccountServiceImpl.transferAnnotation]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; 'transactionManager',-java.lang.Exception
o.s.j.d.DataSourceTransactionManager     : Acquired Connection [com.mysql.jdbc.JDBC4Connection@185f0a96] for JDBC transaction
o.s.j.d.DataSourceTransactionManager     : Switching JDBC Connection [com.mysql.jdbc.JDBC4Connection@185f0a96] to manual commit
org.mybatis.spring.SqlSessionUtils       : Creating a new SqlSession
org.mybatis.spring.SqlSessionUtils       : Registering transaction synchronization for SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@39615e42]
o.m.s.t.SpringManagedTransaction         : JDBC Connection [com.mysql.jdbc.JDBC4Connection@185f0a96] will be managed by Spring
i.i.t.o.d.AccountDAO.selectByPrimaryKey  : ==>  Preparing: select id, nickname, username, `password`, balance, create_time, update_time from account where id = ?
i.i.t.o.d.AccountDAO.selectByPrimaryKey  : ==> Parameters: 1(Long)
i.i.t.o.d.AccountDAO.selectByPrimaryKey  : <==      Total: 1
org.mybatis.spring.SqlSessionUtils       : Releasing transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@39615e42]
org.mybatis.spring.SqlSessionUtils       : Fetched SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@39615e42] from current transaction
i.i.t.o.d.AccountDAO.selectByPrimaryKey  : ==>  Preparing: select id, nickname, username, `password`, balance, create_time, update_time from account where id = ?
i.i.t.o.d.AccountDAO.selectByPrimaryKey  : ==> Parameters: 2(Long)
i.i.t.o.d.AccountDAO.selectByPrimaryKey  : <==      Total: 1
org.mybatis.spring.SqlSessionUtils       : Releasing transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@39615e42]
org.mybatis.spring.SqlSessionUtils       : Fetched SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@39615e42] from current transaction
i.i.t.o.d.A.updateByPrimaryKeySelective  : ==>  Preparing: update account SET nickname = ?, username = ?, `password` = ?, balance = ?, create_time = ?, update_time = ? where id = ?
i.i.t.o.d.A.updateByPrimaryKeySelective  : ==> Parameters: 小一(String), xiaoyi(String), 123456(String), 877.00(BigDecimal), 2020-01-09T17:04:28(LocalDateTime), 2020-01-09T17:44:33(LocalDateTime), 1(Long)
i.i.t.o.d.A.updateByPrimaryKeySelective  : <==    Updates: 1
org.mybatis.spring.SqlSessionUtils       : Releasing transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@39615e42]
org.mybatis.spring.SqlSessionUtils       : Fetched SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@39615e42] from current transaction
i.i.t.o.d.A.updateByPrimaryKeySelective  : ==>  Preparing: update account SET nickname = ?, username = ?, `password` = ?, balance = ?, create_time = ?, update_time = ? where id = ?
i.i.t.o.d.A.updateByPrimaryKeySelective  : ==> Parameters: 小二(String), xiaoer(String), 123456(String), 223.00(BigDecimal), 2020-01-09T17:04:40(LocalDateTime), 2020-01-09T17:04:40(LocalDateTime), 2(Long)
i.i.t.o.d.A.updateByPrimaryKeySelective  : <==    Updates: 1
org.mybatis.spring.SqlSessionUtils       : Releasing transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@39615e42]
org.mybatis.spring.SqlSessionUtils       : Transaction synchronization committing SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@39615e42]
org.mybatis.spring.SqlSessionUtils       : Transaction synchronization deregistering SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@39615e42]
org.mybatis.spring.SqlSessionUtils       : Transaction synchronization closing SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@39615e42]
o.s.j.d.DataSourceTransactionManager     : Initiating transaction commit
o.s.j.d.DataSourceTransactionManager     : Committing JDBC transaction on Connection [com.mysql.jdbc.JDBC4Connection@185f0a96]
o.s.j.d.DataSourceTransactionManager     : Releasing JDBC Connection [com.mysql.jdbc.JDBC4Connection@185f0a96] after transaction
m.m.a.RequestResponseBodyMethodProcessor : Using 'text/html', given [text/html, application/xhtml+xml, image/webp, image/apng, application/xml;q=0.9, application/signed-exchange;v=b3;q=0.9, */*;q=0.8] and supported [text/plain, */*, text/plain, */*, application/json, application/*+json, application/json, application/*+json]
m.m.a.RequestResponseBodyMethodProcessor : Writing ["转账成功!"]
o.s.web.servlet.DispatcherServlet        : Completed 200 OK

  1. GET 请求到 /api/account/transfer/annotation接口 然后调用service方法
  2. 根据写的Transactional注解的设置 创建一个新事务
  3. 选用JDBC连接 然后创建 SqlSession
  4. 为SqlSession注册事务同步
  5. SQL操作
  6. 然后把事务提交
  7. 最后释放资源。完成方法调用
  8. 接口返回200
o.s.web.servlet.DispatcherServlet        : GET "/api/account/transfer/annotation?source=1&target=2&amount=123", parameters={masked}
s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to io.ilss.transaction.onedatasource.web.AccountController#transferAnnotation(Long, Long, String)
o.s.j.d.DataSourceTransactionManager     : Creating new transaction with name [io.ilss.transaction.onedatasource.service.impl.AccountServiceImpl.transferAnnotation]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; 'transactionManager',-java.lang.Exception
o.s.j.d.DataSourceTransactionManager     : Acquired Connection [com.mysql.jdbc.JDBC4Connection@1b6963ec] for JDBC transaction
o.s.j.d.DataSourceTransactionManager     : Switching JDBC Connection [com.mysql.jdbc.JDBC4Connection@1b6963ec] to manual commit
org.mybatis.spring.SqlSessionUtils       : Creating a new SqlSession
org.mybatis.spring.SqlSessionUtils       : Registering transaction synchronization for SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@66240e58]
o.m.s.t.SpringManagedTransaction         : JDBC Connection [com.mysql.jdbc.JDBC4Connection@1b6963ec] will be managed by Spring
i.i.t.o.d.AccountDAO.selectByPrimaryKey  : ==>  Preparing: select id, nickname, username, `password`, balance, create_time, update_time from account where id = ?
i.i.t.o.d.AccountDAO.selectByPrimaryKey  : ==> Parameters: 1(Long)
i.i.t.o.d.AccountDAO.selectByPrimaryKey  : <==      Total: 1
org.mybatis.spring.SqlSessionUtils       : Releasing transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@66240e58]
org.mybatis.spring.SqlSessionUtils       : Fetched SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@66240e58] from current transaction
i.i.t.o.d.AccountDAO.selectByPrimaryKey  : ==>  Preparing: select id, nickname, username, `password`, balance, create_time, update_time from account where id = ?
i.i.t.o.d.AccountDAO.selectByPrimaryKey  : ==> Parameters: 2(Long)
i.i.t.o.d.AccountDAO.selectByPrimaryKey  : <==      Total: 1
org.mybatis.spring.SqlSessionUtils       : Releasing transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@66240e58]
org.mybatis.spring.SqlSessionUtils       : Fetched SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@66240e58] from current transaction
i.i.t.o.d.A.updateByPrimaryKeySelective  : ==>  Preparing: update account SET nickname = ?, username = ?, `password` = ?, balance = ?, create_time = ?, update_time = ? where id = ?
i.i.t.o.d.A.updateByPrimaryKeySelective  : ==> Parameters: 小一(String), xiaoyi(String), 123456(String), 754.00(BigDecimal), 2020-01-09T17:04:28(LocalDateTime), 2020-01-09T17:44:33(LocalDateTime), 1(Long)
i.i.t.o.d.A.updateByPrimaryKeySelective  : <==    Updates: 1
org.mybatis.spring.SqlSessionUtils       : Releasing transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@66240e58]
org.mybatis.spring.SqlSessionUtils       : Transaction synchronization deregistering SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@66240e58]
org.mybatis.spring.SqlSessionUtils       : Transaction synchronization closing SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@66240e58]
o.s.j.d.DataSourceTransactionManager     : Initiating transaction rollback
o.s.j.d.DataSourceTransactionManager     : Rolling back JDBC transaction on Connection [com.mysql.jdbc.JDBC4Connection@1b6963ec]
o.s.j.d.DataSourceTransactionManager     : Releasing JDBC Connection [com.mysql.jdbc.JDBC4Connection@1b6963ec] after transaction
o.s.web.servlet.DispatcherServlet        : Failed to complete request: java.lang.RuntimeException: annotation error!
o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is 
java.lang.RuntimeException: annotation error!
                            .......
o.a.c.c.C.[Tomcat].[localhost]           : Processing ErrorPage[errorCode=0, location=/error]
o.s.web.servlet.DispatcherServlet        : "ERROR" dispatch for GET "/error?source=1&target=2&amount=123", parameters={masked}
s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController#errorHtml(HttpServletRequest, HttpServletResponse)
o.s.w.s.v.ContentNegotiatingViewResolver : Selected 'text/html' given [text/html, text/html;q=0.8]
o.s.web.servlet.DispatcherServlet        : Exiting from "ERROR" dispatch, status 500

  1. GET 请求到 /api/account/transfer/annotation接口 然后调用service方法
  2. 根据写的Transactional注解的设置 创建一个新事务
  3. 选用JDBC连接 然后创建 SqlSession
  4. 为SqlSession注册事务同步
  5. SQL操作:可以从日志看到,执行到第一个跟新操作发生错误
  6. 直接回滚Rolling back JDBC transaction on Connection后打印错误日志。后面的第二个更新操作也就没了
  7. 方法异常退出,接口500

3.4 编程实现事务管理

  1. 创建事务定义TransactionDefinition transactionDefinition = new DefaultTransactionDefinition();
  2. 设置事务属性:如传播属性、隔离属性等
  3. 通过TransactionManager开启事务
  4. 执行业务代码
  5. 提交事务 / 处理回滚

// todo: 下一篇多数据源事务管理


关于我

上一篇下一篇

猜你喜欢

热点阅读