美文网首页
spring笔记-TransactionProxyFactory

spring笔记-TransactionProxyFactory

作者: 兴浩 | 来源:发表于2018-06-25 11:51 被阅读75次

    概念
    1.DefaultTransactionDefinition

    1. TransactionStatus

    3.PlatformTransactionManager

    事务管理器,用于事务的提交和回滚

    1.使用PlatformTransactionManager提交

        public void testPlatformTransactionManager() {
            DefaultTransactionDefinition def = new DefaultTransactionDefinition();
            def.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED);
            def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
            TransactionStatus status = txManager.getTransaction(def);
            jdbcTemplate.update(UPDATE_SQL,"3");
            try {
                jdbcTemplate.update(INSERT_SQL, "4");
                txManager.commit(status);
            } catch (RuntimeException e) {
                txManager.rollback(status);
            }
        }
    

    2.使用低级别api来提交事务

    获取Connection来操作sql语句

        public void testPlatformTransactionManagerForLowLevel1() {
            DefaultTransactionDefinition def = new DefaultTransactionDefinition();
            def.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED);
            def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
            TransactionStatus status = txManager.getTransaction(def);
            Connection conn = DataSourceUtils.getConnection(dataSource);
            try {
                {
                    PreparedStatement pstmt = conn.prepareStatement(UPDATE_SQL);
                    pstmt.setString(1, "update_test");
                    pstmt.execute();
                }
                {
                    PreparedStatement pstmt = conn.prepareStatement(INSERT_SQL);
                    pstmt.setString(1, "insert_test");
                    pstmt.execute();
                }
                txManager.commit(status);
            } catch (Exception e) {
                status.setRollbackOnly();
                txManager.rollback(status);
            } finally {
                DataSourceUtils.releaseConnection(conn, dataSource);
            }
        }
    

    3.TransactionTemplate

    TransactionTemplate继承自DefaultTransactionDefinition,提内部提供了PlatformTransactionManager的模板方法

        public void testTransactionTemplate() {
    
            TransactionTemplate transactionTemplate = new TransactionTemplate(txManager);
            transactionTemplate.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED);
            transactionTemplate.execute(new TransactionCallbackWithoutResult() {
                @Override
                protected void doInTransactionWithoutResult(TransactionStatus status) {
                    jdbcTemplate.update(UPDATE_SQL, "update_testTransactionTemplate");
                    jdbcTemplate.update(INSERT_SQL, "insert_testTransactionTemplate");
                }
            });
        }
    
    

    4.TransactionProxyFactoryBean

    使用代理的方式处理事务

    public interface ITestService {
    
        void save(TestBean bean);
    }
    
    @Service
    public class TestService extends BaseJdbcDaoSupport implements ITestService {
    
    
        private static final String UPDATE_SQL = "update tx_test set name = ? where id=1";
        private static final String INSERT_SQL = "insert into tx_test(name) values(?)";
    
        @Override
        @Transactional(readOnly = false)
        public void save(TestBean bean) {
    
            getJdbcTemplate().update(UPDATE_SQL, "update" + bean.getName()+System.currentTimeMillis());
            getJdbcTemplate().update(INSERT_SQL, "insert" + bean.getName()+System.currentTimeMillis());
        }
    }
    
        @Bean("testServiceTransactionProxyFactoryBean")
        public TransactionProxyFactoryBean getProxyFactoryBean(TestService service,
                                                               PlatformTransactionManager txManager)
        {
            TransactionProxyFactoryBean proxyFactoryBean=new TransactionProxyFactoryBean();
            proxyFactoryBean.setTarget(service);
            proxyFactoryBean.setTransactionManager(txManager);
    
            Properties prop=new Properties();
            prop.setProperty("save*","PROPAGATION_REQUIRED");
            proxyFactoryBean.setTransactionAttributes(prop);
            return proxyFactoryBean;
        }
    
        public void testTransactionProxyFactoryBean() {
    
            ITestService testService=SpringContextUtil.getBean("testServiceTransactionProxyFactoryBean");
            TestBean bean=new TestBean();
            bean.setName("bean");
            testService.save(bean);
        }
    

    5.TransactionProxyFactoryBean解析

    这个是解析的重点

    1.TransactionInterceptor
    事务处理增强
    2.TransactionAttributeSourcePointcut
    事务处理属性源切点
    3.TransactionAttributeSourceAdvisor
    事务处理属性源切面

    TransactionAttributeSourceAdvisor默认由TransactionInterceptor和TransactionAttributeSourcePointcut组成

    5.1 TransactionAttributeSource

    TransactionAttributeSource接口用于获取TransactionAttribute属性

    public interface TransactionAttributeSource {
    
        TransactionAttribute getTransactionAttribute(Method method, Class<?> targetClass);
    
    }
    

    5.2 TransactionAttribute继承自TransactionDefinition,扩展了2个功能,

    DefaultTransactionAttribute是默认实现

    public interface TransactionAttribute extends TransactionDefinition {
    
        String getQualifier();
    
        boolean rollbackOn(Throwable ex);
    
    }
    
    public class DefaultTransactionAttribute extends DefaultTransactionDefinition implements TransactionAttribute {
    }
    

    5.3 TransactionAttributeSource的实现

    1.NameMatchTransactionAttributeSource

    通过设置Properties来实现

        public void setTransactionAttributes(Properties transactionAttributes) {
            NameMatchTransactionAttributeSource tas = new NameMatchTransactionAttributeSource();
            tas.setProperties(transactionAttributes);
            this.transactionAttributeSource = tas;
        }
    
            Properties prop=new Properties();
            prop.setProperty("save*","PROPAGATION_REQUIRED");
            proxyFactoryBean.setTransactionAttributes(prop);
    

    2.AnnotationTransactionAttributeSource

    通过解析注解的方式来实现,其是通过TransactionAnnotationParser来解析实现

    3.TransactionAnnotationParser

    我们只需要关注SpringTransactionAnnotationParser,其实现了对Transactional注解的解析

        public TransactionAttribute parseTransactionAnnotation(Transactional ann) {
            return parseTransactionAnnotation(AnnotationUtils.getAnnotationAttributes(ann, false, false));
        }
    
        protected TransactionAttribute parseTransactionAnnotation(AnnotationAttributes attributes) {
            RuleBasedTransactionAttribute rbta = new RuleBasedTransactionAttribute();
            Propagation propagation = attributes.getEnum("propagation");
            rbta.setPropagationBehavior(propagation.value());
            Isolation isolation = attributes.getEnum("isolation");
            rbta.setIsolationLevel(isolation.value());
            rbta.setTimeout(attributes.getNumber("timeout").intValue());
            rbta.setReadOnly(attributes.getBoolean("readOnly"));
            rbta.setQualifier(attributes.getString("value"));
            ArrayList<RollbackRuleAttribute> rollBackRules = new ArrayList<RollbackRuleAttribute>();
            Class<?>[] rbf = attributes.getClassArray("rollbackFor");
            for (Class<?> rbRule : rbf) {
                RollbackRuleAttribute rule = new RollbackRuleAttribute(rbRule);
                rollBackRules.add(rule);
            }
            String[] rbfc = attributes.getStringArray("rollbackForClassName");
            for (String rbRule : rbfc) {
                RollbackRuleAttribute rule = new RollbackRuleAttribute(rbRule);
                rollBackRules.add(rule);
            }
            Class<?>[] nrbf = attributes.getClassArray("noRollbackFor");
            for (Class<?> rbRule : nrbf) {
                NoRollbackRuleAttribute rule = new NoRollbackRuleAttribute(rbRule);
                rollBackRules.add(rule);
            }
            String[] nrbfc = attributes.getStringArray("noRollbackForClassName");
            for (String rbRule : nrbfc) {
                NoRollbackRuleAttribute rule = new NoRollbackRuleAttribute(rbRule);
                rollBackRules.add(rule);
            }
            rbta.getRollbackRules().addAll(rollBackRules);
            return rbta;
        }
    

    使用该方式就不再需要在TransactionProxyFactoryBean中调用setTransactionAttributes方法设置熟悉,直接在方法上加注解就行

        @Override
        @Transactional(readOnly = false,propagation = Propagation.SUPPORTS,transactionManager = "test")
        public void save(TestBean bean) {
    
            getJdbcTemplate().update(UPDATE_SQL, "update" + bean.getName()+System.currentTimeMillis());
            getJdbcTemplate().update(INSERT_SQL, "insert" + bean.getName()+System.currentTimeMillis());
        }
    

    相关文章

      网友评论

          本文标题:spring笔记-TransactionProxyFactory

          本文链接:https://www.haomeiwen.com/subject/rageyftx.html