zoukankan      html  css  js  c++  java
  • Spring框架5:事务和动态代理

    本系列笔记均是对b站教程https://www.bilibili.com/video/av47952931 的学习笔记,非本人原创

    enter description here

    事务

    我们在service中加一个转账的功能

    public void transfer(String sourceName, String targetName, Float money) {
                Account source = accountDao.findAccountByName(sourceName);
                Account target = accountDao.findAccountByName(targetName);
                source.setMoney(source.getMoney() - money);
                target.setMoney(target.getMoney() + money);
                accountDao.updateAccount(source);
                accountDao.updateAccount(target);
        }
    
    貌似没什么问题吧,一套下来就是转账的流程。但是实际上这样写是会出问题的,就是不符合事务的一致性,可能会出现加钱失败了,减钱的事务还在继续。例如将上面的代码稍作改动:
    
    	source.setMoney(source.getMoney() - money);
    	int a=1/0;
        target.setMoney(target.getMoney() + money);
    

    毫无疑问上面是会报错的,但是这时加钱的操作就不会进行了,但是减钱的操作已经做完了,这就导致了数据的异常。
    导致这一现象的原因我们可以从accountDao的代码片段中看出来:

        public void updateAccount(Account account) {
            try {
                //name和money都是可变的,不变的是id,也就是主键,所以查找的时候要查id
                runner.update("update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());
            } catch (Exception e) {
                throw new RuntimeException();
            }
        }
    

    每一次操作都是调用一次runner.update,而注意我们在bean.xml对runner的配置

        <!-- queryRunner不能是单例对象,防止多线程出现问题-->
        <bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
            <!-- 注入数据源 -->
            <constructor-arg name="ds" ref="dataSoure"></constructor-arg>
        </bean>
    

    runner是一个多例对象,每一个调用都是一个单独的runner,对数据库使用的是不同的连接,所以他们是不同的事务。解决方法就是让所有操作共用一个连接,而不是像我们在xml中设置的那样使用多例对象。这里的方法就是使用ThreadLocal对象把Connection和当前线程绑定从而使得一个线程只有一个能控制事务的对象。
    关于ThreadLocal,可以看这篇文章:https://www.cnblogs.com/jiading/articles/12337399.html
    来看我们的解决方案
    首先,我们新建了一个连接的工具类,用于从数据源中获取连接,并且和线程相绑定
    ConnectionUtils.java

    package com.jiading.utils;
    
    import javax.sql.DataSource;
    import java.sql.Connection;
    
    /*
    连接的工具类,用于从数据源中获取连接并实现和线程的绑定
     */
    public class ConnectionUtils {
        private ThreadLocal<Connection> tl = new ThreadLocal<Connection>();//新建一个ThreadLocal对象,它存放的是Connection类型的对象
    /*
    设置datasource的set函数,以便于之后spring进行注入
    */
        public void setDataSource(DataSource dataSource) {
            this.dataSource = dataSource;
        }
    
        /*
            获取当前线程上的连接
             */
        private DataSource dataSource;
    	
    //通过对connection的get方法
        public Connection getThreadConnection() {
            //1. 先从ThreadLocal上获取
            Connection conn = tl.get();
            try {
                //2. 判断当前线程上是否有连接,没有就创建一个
                if (conn == null) {
                    //3.从数据源中获取一个连接,并和线程绑定
                    conn = dataSource.getConnection();
                    //4. 存入连接
                    tl.set(conn);//现在ThreadLocal就和这个Connection对象绑定了
                }
                //5. 返回当前线程上的连接
                return conn;
            }catch(Exception e){
                throw new RuntimeException();
            }
        }
        /*
        把连接和线程解绑
         */
        public void removeConnection(){
            tl.remove();
        }
    }
    

    我们还需要另外一个工具类来帮忙实现和事务相关的操作。
    TransactionManager.java:(注:transaction就是事务的意思)

    package com.jiading.utils;
    
    import java.sql.Connection;
    import java.sql.SQLException;
    
    /*
    和事务管理相关的工具类,它包含了开启事务、提交事务、回滚事务和释放连接的方法
     */
    public class TransactionManager {
    /*
    需要用到ConnectionUtils,这里设置一个set函数以便于spring注入
    */
        public void setConnectionUtils(ConnectionUtils connectionUtils) {
            this.connectionUtils = connectionUtils;
        }
    
        private ConnectionUtils connectionUtils;
        /*
        开启一个连接,并且设置它的自动commit关闭
         */
        public void beginTransaction(){
            try {
                connectionUtils.getThreadConnection().setAutoCommit(false);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    	/*
    	手动提交
    	*/
        public void commit(){
            try {
                connectionUtils.getThreadConnection().commit();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    	/*
    	回滚
    	*/
        public void rollback(){
            try {
                connectionUtils.getThreadConnection().rollback();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        public void release(){
            try {
                connectionUtils.getThreadConnection().close();//将连接放回连接池
                connectionUtils.removeConnection();//解绑
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    

    这里的工具类只负责事务相关的操作,它默认在一个线程中通过connectionUtils.getThreadConnection()获取的connection对象都是同一个,所以它才能如此放心地在每一个方法中都调用一遍connectionUtils.getThreadConnection()来获取对象。而对于ConnectionUtils,它和单例对象不一样,单例对象不能满足多线程使用的要求;但是也和多例对象不一样,多例对象不能区分是不同线程调用函数一个线程内多次调用。
    对于Dao层,相应地方法的实现也变了:

    package com.jiading.dao.impl;
    
    import com.jiading.dao.IAccountDao;
    import com.jiading.domain.Account;
    import com.jiading.utils.ConnectionUtils;
    import org.apache.commons.dbutils.QueryRunner;
    import org.apache.commons.dbutils.handlers.BeanHandler;
    import org.apache.commons.dbutils.handlers.BeanListHandler;
    
    import java.sql.SQLException;
    import java.util.List;
    
    public class AccountDaoImpl implements IAccountDao {
        public void setRunner(QueryRunner runner) {
    
            this.runner = runner;
        }
    
        private QueryRunner runner;
    
        public void setConnectionUtils(ConnectionUtils connectionUtils) {
            this.connectionUtils = connectionUtils;
        }
    
        private ConnectionUtils connectionUtils;//需要使用这个连接工具类
    
        public List<Account> findAllAccount() {
            try {
                return runner.query(connectionUtils.getThreadConnection(),"select * from account", new BeanListHandler<Account>(Account.class));
            } catch (Exception e) {
                throw new RuntimeException();
            }
        }
    
        public Account findAccountById(Integer accountId) {
            try {
                return runner.query(connectionUtils.getThreadConnection(),"select * from account where id=?", new BeanHandler<Account>(Account.class),accountId);
            } catch (Exception e) {
                throw new RuntimeException();
            }
        }
    
        public void saveAccount(Account acc) {
            try {
                runner.update(connectionUtils.getThreadConnection(),"insert into account(name,money) values(?,?)",acc.getName(),acc.getMoney());
            } catch (Exception e) {
                throw new RuntimeException();
            }
        }
    
        public void updateAccount(Account account) {
            try {
                //name和money都是可变的,不变的是id,也就是主键,所以查找的时候要查id
                runner.update(connectionUtils.getThreadConnection(),"update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());
            } catch (Exception e) {
                throw new RuntimeException();
            }
        }
    
        public void deleteAccount(Integer accountId) {
            try {
                runner.update(connectionUtils.getThreadConnection(),"delete from account where id=?",accountId);
            } catch (Exception e) {
                throw new RuntimeException();
            }
        }
    
        public Account findAccountByName(String AccountName) {
            /*
            有唯一结果就返回
            没有结果就返回Null
            如果结果集合超过一个就抛出异常
             */
            try {
                List<Account>accounts = runner.query(connectionUtils.getThreadConnection(),"select * from account where name=?", new BeanListHandler<Account>(Account.class), AccountName);
                if(accounts==null || accounts.size()==0){
                    return null;
                }
                if(accounts.size()>1){
                    throw new RuntimeException("结果集不唯一");
                }
                return accounts.get(0);
            } catch (Exception e) {
                throw new RuntimeException();
            }
        }
    }
    

    这里有个地方要注意,因为我们是采用工具类获取连接对象的并传入runner了,所以不能再向runner中注入connection了,所以runner.query()的参数多了一个,相应的bean.xml中也要修改:

        <!-- queryRunner不能是单例对象,防止多线程出现问题-->
        <bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
        </bean>
    

    这里要注意,Dao中并没有用到我们写的那个事务的工具类,因为Dao是持久层,只负责sql语句的执行,而我们所说的事务是和我们的业务相关的,它应该是在service中:

    package com.jiading.service.impl;
    
    import com.jiading.dao.IAccountDao;
    import com.jiading.domain.Account;
    import com.jiading.service.IAccountService;
    import com.jiading.utils.TransactionManager;
    
    import java.util.List;
    
    /*
    事务的控制应该是在业务层的,而不是持久层
     */
    public class AccountServiceImpl implements IAccountService {
        public void setAccountDao(IAccountDao accountDao) {
            this.accountDao = accountDao;
        }
    
        private IAccountDao accountDao;
    
        public void setTxManager(TransactionManager txManager) {
            this.txManager = txManager;
        }
    
        private TransactionManager txManager;
    
        public List<Account> findAllAccount() {
            try {
                //1.开启事务
                txManager.beginTransaction();
                //2.执行操作
                List<Account> allAccount = accountDao.findAllAccount();
                //3.提交事务
                txManager.commit();
                //4.返回结果
                return allAccount;
            } catch (Exception e) {
                //5. 回滚事务
                txManager.rollback();
                throw new RuntimeException(e);
            } finally {
                //6. 释放连接
                txManager.release();
            }
    
        }
    
        public Account findAccountById(Integer accountId) {
            try {
                //1.开启事务
                txManager.beginTransaction();
                //2.执行操作
                Account accountById = accountDao.findAccountById(accountId);
                //3.提交事务
                txManager.commit();
                //4.返回结果
                return accountById;
            } catch (Exception e) {
                //5. 回滚事务
                txManager.rollback();
                throw new RuntimeException(e);
            } finally {
                //6. 释放连接
                txManager.release();
            }
        }
    
        public void saveAccount(Account acc) {
            try {
                //1.开启事务
                txManager.beginTransaction();
                //2.执行操作
                accountDao.saveAccount(acc);
                //3.提交事务
                txManager.commit();
                //4.返回结果
            } catch (Exception e) {
                //5. 回滚事务
                txManager.rollback();
                throw new RuntimeException(e);
            } finally {
                //6. 释放连接
                txManager.release();
            }
        }
    
        public void updateAccount(Account account) {
            try {
                //1.开启事务
                txManager.beginTransaction();
                //2.执行操作
                accountDao.updateAccount(account);
                //3.提交事务
                txManager.commit();
                //4.返回结果
            } catch (Exception e) {
                //5. 回滚事务
                txManager.rollback();
                throw new RuntimeException(e);
            } finally {
                //6. 释放连接
                txManager.release();
            }
        }
    
        public void deleteAccount(Integer accountId) {
            try {
                //1.开启事务
                txManager.beginTransaction();
                //2.执行操作
                accountDao.deleteAccount(accountId);
                //3.提交事务
                txManager.commit();
                //4.返回结果
            } catch (Exception e) {
                //5. 回滚事务
                txManager.rollback();
                throw new RuntimeException(e);
            } finally {
                //6. 释放连接
                txManager.release();
            }
        }
    
        public void transfer(String sourceName, String targetName, Float money) {
            try {
                //1.开启事务
                txManager.beginTransaction();
                //2.执行操作
                Account source = accountDao.findAccountByName(sourceName);
                Account target = accountDao.findAccountByName(targetName);
                source.setMoney(source.getMoney() - money);
                target.setMoney(target.getMoney() + money);
            /*
            这样写是会出问题的,就是不符合事务的一致性,可能会出现加钱失败了,减钱的事务还在继续
            注意:一个连接对应的是一个事务。解决方法就是让所有操作共用一个连接,而不是像我们在xml中设置的那样使用多例对象
            解决方法:
                使用ThreadLocal对象把Connection和当前线程绑定从而使得一个线程只有一个能控制事务的对象
             */
                accountDao.updateAccount(source);
                accountDao.updateAccount(target);
                //3.提交事务
                txManager.commit();
                //4.返回结果;
            } catch (Exception e) {
                //5. 回滚事务
                txManager.rollback();
                throw new RuntimeException(e);
            } finally {
                //6. 释放连接
                txManager.release();
            }
        }
    }
    

    我们还需要将自己写的工具类加入xml中以便于spring进行注入:

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd">
        <!-- 配置数据源 -->
        <bean id="dataSoure" class="com.mchange.v2.c3p0.ComboPooledDataSource">
            <!-- 连接数据库的必备信息-->
            <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/jd_learning"></property>
        <property name="user" value="root"></property>
        <property name="password" value="<密码>"></property>
        </bean>
    
        <!-- queryRunner不能是单例对象,防止多线程出现问题-->
        <bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
        </bean>
    
        <bean id="accountDao" class="com.jiading.dao.impl.AccountDaoImpl">
            <property name="runner" ref="runner"></property>
            <property name="connectionUtils" ref="connectionUtils"></property>
        </bean>
    
        <bean id="accountService" class="com.jiading.service.impl.AccountServiceImpl">
            <!-- 注入dao对象-->
            <property name="accountDao" ref="accountDao"></property>
            <property name="txManager" ref="txManager"></property>
        </bean>
        <!-- 配置connection工具类 ConnectionUtils-->
        <bean id="connectionUtils" class="com.jiading.utils.ConnectionUtils">
            <property name="dataSource" ref="dataSoure"></property>
        </bean>
        <!-- 配置事务管理器-->
        <bean id="txManager" class="com.jiading.utils.TransactionManager">
            <property name="connectionUtils" ref="connectionUtils"></property>
        </bean>
    </beans>
    

    这样我们就在允许多线程的前提下实现了数据库的事务,但是显然,这么写是有一些问题的:

    • 项目变得非常地复杂
    • 重复代码太多,特别是service中,每一个操作都要完成全套的事务相关操作
      对于这些问题,我们可以使用动态代理进行解决

    动态代理

    Java动态代理的实现请看这篇文章:https://www.cnblogs.com/jiading/p/12343777.html
    动态代理实现
    BeanFactory.java:

    package com.jiading.factory;
    
    import com.jiading.service.IAccountService;
    import com.jiading.utils.TransactionManager;
    
    import java.lang.reflect.InvocationHandler;
    import java.lang.reflect.Method;
    import java.lang.reflect.Proxy;
    
    /*
    用于创建service的代理对象的工厂
     */
    public class BeanFactory {
        public void setAccountService(IAccountService accountService) {
            this.accountService = accountService;
        }
    
        private IAccountService accountService;
        public void setTxManager(TransactionManager txManager) {
            this.txManager = txManager;
        }
    
        private TransactionManager txManager;
        /*
        获取service的代理对象
         */
        public IAccountService getAccountService(){
            IAccountService accountServiceProxy=(IAccountService)Proxy.newProxyInstance(accountService.getClass().getClassLoader(), accountService.getClass().getInterfaces(), new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    /*
                    添加事务的支持
                     */
                    Object rtValue=null;
                    try {
                        //1.开启事务
                        txManager.beginTransaction();
                        //2.执行操作
                        rtValue = method.invoke(accountService, args);
                        //3.提交事务
                        txManager.commit();
                        //4.返回结果
                        return rtValue;
                    } catch (Exception e) {
                        //5. 回滚事务
                        txManager.rollback();
                        throw new RuntimeException(e);
                    } finally {
                        //6. 释放连接
                        txManager.release();
                    }
                }
            });
            return accountServiceProxy;
        }
    }
    

    这应该比较好理解,就是将service的一个方法放在一个事务中,这样service中的transfer的各个步骤就是在一个事务中了
    相应地,service中的事务控制就可以删除了。这就使得service对象的编写只需要考虑业务需求即可
    AccountServiceImpl.java

    package com.jiading.service.impl;
    
    import com.jiading.dao.IAccountDao;
    import com.jiading.domain.Account;
    import com.jiading.service.IAccountService;
    import com.jiading.utils.TransactionManager;
    
    import java.util.List;
    
    /*
    事务的控制应该是在业务层的,而不是持久层
     */
    public class AccountServiceImpl implements IAccountService {
        public void setAccountDao(IAccountDao accountDao) {
            this.accountDao = accountDao;
        }
    
        private IAccountDao accountDao;
    
        public void setTxManager(TransactionManager txManager) {
            this.txManager = txManager;
        }
    
        private TransactionManager txManager;
    
        @Override
        public List<Account> findAllAccount() {
            List<Account> allAccount = accountDao.findAllAccount();
            return allAccount;
        }
    
        @Override
        public Account findAccountById(Integer accountId) {
            Account accountById = accountDao.findAccountById(accountId);
            return accountById;
    
        }
    
        @Override
        public void saveAccount(Account acc) {
                accountDao.saveAccount(acc);
        }
    
        @Override
        public void updateAccount(Account account) {
                accountDao.updateAccount(account);
        }
    
        @Override
        public void deleteAccount(Integer accountId) {
                accountDao.deleteAccount(accountId);
        }
    
        @Override
        public void transfer(String sourceName, String targetName, Float money) {
            Account source = accountDao.findAccountByName(sourceName);
            Account target = accountDao.findAccountByName(targetName);
            source.setMoney(source.getMoney() - money);
            target.setMoney(target.getMoney() + money);
            accountDao.updateAccount(source);
            accountDao.updateAccount(target);
        }
    }
    

    还需要到bean.xml中配置一下
    因为不需要在service中使用事务控制了,所以就不用在z其中注入事务控制器了:

        <bean id="accountService" class="com.jiading.service.impl.AccountServiceImpl">
            <!-- 注入dao对象-->
            <property name="accountDao" ref="accountDao"></property>
        </bean>
    

    需要配置一下代理类和beanFactory:

    <!--配置代理的service-->
        <bean id="proxyAccountService" factory-bean="beanFactory" factory-method="getAccountService"></bean>
        <!-- 配置beanFactory-->
        <bean id="beanFactory" class="com.jiading.factory.BeanFactory">
            <property name="accountService" ref="accountService"></property>
            <property name="txManager" ref="txManager"></property>
        </bean>
    

    这样做的好处之前已经说过了,但是有没有什么缺点呢?有的,就是实现和配置起来很复杂。使用接下来我们就要介绍spring中的AOP,我们之后可以使用spring框架已经实现的功能,仅需要做配置就好

  • 相关阅读:
    6 全局锁和表锁
    oracle ogg--ogg搭建过程中遇到的错误及处理
    5 深入浅出索引(下)
    4 深入浅出索引(上)
    oracle ogg 单实例双向-新增表,修改表结构(oracle-oracle
    oracle ogg 单实例双向复制搭建(oracle-oracle)--Oracle GoldenGate
    Iview 中 获取 Menu 导航菜单 选中的值
    idea中git分支的使用
    vue使用axios进行ajax请求
    web前端_Vue框架_设置浏览器上方的标题和图标
  • 原文地址:https://www.cnblogs.com/jiading/p/12368808.html
Copyright © 2011-2022 走看看