Spring 实现你自己的事务同步

在《Spring Transaction 分析事务属性(事务的基本概念、配置)》基础上



将介绍如何实现你自己的事务同步,只要是活动的事务状态发生变化就会收到TransactionSynchronizationManager的回调。

书中的demo:
使用TransactionSynchronizationManager注册了TransactionSynchronization回调,同时MyTransactionSynchronizationAdapter会根据事务的完成状态去调用MySession.beginTransaction()、MySession.commit()或MySession.rollback()方法。


模拟一个session类:
view plain copy to clipboard print ?
  1. packagecn.partner4java.myptm;
  2. importjava.io.Serializable;
  3. /**
  4. * 模拟一个session类
  5. * @author partner4java
  6. *
  7. */
  8. publicclassMySession {
  9. /** 用来标识一个session */
  10. privateLong sessionId;
  11. publicvoidsave(Serializable entity){
  12. System.out.println(sessionId +":save");
  13. }
  14. publicvoidbeginTransaction(){
  15. System.out.println(sessionId +":beginTransaction");
  16. }
  17. publicvoidcommit(){
  18. System.out.println(sessionId +":commit");
  19. }
  20. publicvoidrollback(){
  21. System.out.println(sessionId +":rollback");
  22. }
  23. publicLong getSessionId() {
  24. returnsessionId;
  25. }
  26. publicvoidsetSessionId(Long sessionId) {
  27. this.sessionId = sessionId;
  28. }
  29. @Override
  30. publicString toString() {
  31. return"MySession [sessionId="+ sessionId +"]";
  32. }
  33. }

简单模拟SessionFactory:
view plain copy to clipboard print ?
  1. packagecn.partner4java.myptm;
  2. importorg.springframework.transaction.support.TransactionSynchronization;
  3. importorg.springframework.transaction.support.TransactionSynchronizationManager;
  4. /**
  5. * 简单模拟SessionFactory
  6. * 通判传递的类都为MySessionFactory而不是MySession,通过MySessionFactory获得当前线程的MySession或者开启一个新的MySession
  7. * @author partner4java
  8. *
  9. */
  10. publicclassMySessionFactory {
  11. /**
  12. * 如果当前线程存在MySession,就使用该MySession,否者开启一个新的MySession
  13. * @return
  14. */
  15. publicMySession getSession(){
  16. //传入this,是因为,我们以当前factory类作为键保存的MySession
  17. if(TransactionSynchronizationManager.hasResource(this)){
  18. returngetCurrentSession();
  19. }else{
  20. returnopenSession();
  21. }
  22. }
  23. /**
  24. * 开启一个新MySession
  25. * @return
  26. */
  27. privateMySession openSession() {
  28. MySession mySession =newMySession();
  29. mySession.setSessionId(System.currentTimeMillis());
  30. //注册进当前线程管理一个Synchronization
  31. TransactionSynchronization transactionSynchronization =newMyTransactionSynchronizationAdapter(this);
  32. TransactionSynchronizationManager.registerSynchronization(transactionSynchronization);
  33. //绑定新开启的一个MySession进当前线程事务管理器
  34. TransactionSynchronizationManager.bindResource(this, mySession);
  35. returnmySession;
  36. }
  37. /**
  38. * 获取当前线程的MySession
  39. * @return
  40. */
  41. privateMySession getCurrentSession() {
  42. MySession mySession = (MySession) TransactionSynchronizationManager.getResource(this);
  43. returnmySession;
  44. }
  45. }

核心事务同步适配器:
view plain copy to clipboard print ?
  1. packagecn.partner4java.myptm;
  2. importorg.springframework.transaction.support.TransactionSynchronizationAdapter;
  3. importorg.springframework.transaction.support.TransactionSynchronizationManager;
  4. /**
  5. * 核心事务同步适配器
  6. * 当方法上面定义了@Transactional注解,那么当每次状态发生时就会调用本同步适配器
  7. * for transaction synchronization callbacks
  8. * @author partner4java
  9. *
  10. */
  11. publicclassMyTransactionSynchronizationAdapterextends
  12. TransactionSynchronizationAdapter {
  13. privateMySessionFactory mySessionFactory;
  14. publicMyTransactionSynchronizationAdapter(MySessionFactory mySessionFactory) {
  15. this.mySessionFactory = mySessionFactory;
  16. }
  17. @Override
  18. publicvoidbeforeCommit(booleanreadOnly) {
  19. //readOnly标识是否是一个只读线程
  20. if(!readOnly){
  21. MySession mySession = (MySession) TransactionSynchronizationManager.getResource(mySessionFactory);
  22. mySession.beginTransaction();
  23. }
  24. }
  25. @Override
  26. publicvoidafterCompletion(intstatus) {
  27. MySession mySession = (MySession) TransactionSynchronizationManager.getResource(mySessionFactory);
  28. if(STATUS_COMMITTED == status) {
  29. mySession.commit();
  30. }
  31. //当然,你还可以定义回滚方法
  32. }
  33. }

调用起的DAO:
view plain copy to clipboard print ?
  1. packagecn.partner4java.dao;
  2. publicinterfaceHelloDao {
  3. publicvoidsaveHello();
  4. }

view plain copy to clipboard print ?
  1. packagecn.partner4java.dao;
  2. importorg.springframework.jdbc.core.support.JdbcDaoSupport;
  3. importorg.springframework.transaction.annotation.Transactional;
  4. importcn.partner4java.myptm.MySessionFactory;
  5. /**
  6. * 一个hello world dao,起到模拟调用自定义事务同步的作用
  7. * @author partner4java
  8. *
  9. */
  10. publicclassHelloDaoImplextendsJdbcDaoSupportimplementsHelloDao {
  11. privateMySessionFactory mySessionFactory;
  12. publicvoidsetMySessionFactory(MySessionFactory mySessionFactory) {
  13. this.mySessionFactory = mySessionFactory;
  14. }
  15. @Transactional
  16. publicvoidsaveHello(){
  17. mySessionFactory.getSession().save(null);
  18. this.getJdbcTemplate().execute("select * from user");
  19. }
  20. }


配置文件:
view plain copy to clipboard print ?
  1. "1.0"encoding="UTF-8"?>
  2. "http://www.springframework.org/schema/beans"
  3. xmlns:aop="http://www.springframework.org/schema/aop"
  4. xmlns:tx="http://www.springframework.org/schema/tx"
  5. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  6. xsi:schemaLocation="
  7. http://www.springframework.org/schema/beans
  8. http://www.springframework.org/schema/beans/spring-beans.xsd
  9. http://www.springframework.org/schema/tx
  10. http://www.springframework.org/schema/tx/spring-tx.xsd
  11. http://www.springframework.org/schema/aop
  12. http://www.springframework.org/schema/aop/spring-aop.xsd">
  13. "dataSource"class="org.springframework.jdbc.datasource.DriverManagerDataSource"destroy-method="close">
  14. "driverClassName"value="com.mysql.jdbc.Driver"/>
  15. "url"value="jdbc:mysql://localhost:3306/springdb"/>
  16. "username"value="root"/>
  17. "password"value="123456"/>
  18. "transactionManager"class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
  19. "dataSource"ref="dataSource"/>
  20. "transactionManager"/>
  21. "mySessionFactory"class="cn.partner4java.myptm.MySessionFactory"/>
  22. "helloDao"class="cn.partner4java.dao.HelloDaoImpl">
  23. "dataSource"ref="dataSource"/>
  24. "mySessionFactory"ref="mySessionFactory">


测试:
view plain copy to clipboard print ?
  1. ApplicationContext ac =newClassPathXmlApplicationContext("/META-INF/spring/myptm.xml");
  2. HelloDao helloDao = (HelloDao) ac.getBean("helloDao");
  3. helloDao.saveHello();
  4. // 后台打印:
  5. // 1322395163008:save
  6. // 1322395163008:beginTransaction
  7. // 1322395163008:commit

总结:有两个核心的Spring类支持了这个功能,TransactionSynchronization接口,TransactionSynchronizationManager类。
TransactionSynchronizationManager负责管理当前线程在资源,资源可以主动绑定到TransactionSynchronizationManager中。
TransactionSynchronization提供了同步调用,当方法上面定义了@Transactional注解,那么当每次状态发生时就会调用本同步适配器。

PlatformTransactionManager的各种实现也是借助了上面这两个类,你可以查阅一下源码。所以,我们自然而然的也可以自己实现一个PlatformTransactionManager,来管理真正的sessionFactory,然后像其他实现一样,交给Spring,然后再给他声明事务。

你可能感兴趣的:(Spring 实现你自己的事务同步)