1. 程式人生 > >使用ThreadLocal搭建支援併發,事務的DAO

使用ThreadLocal搭建支援併發,事務的DAO

ThreadLocal的原理是使用一個hashMap儲存connection,而鍵為當前執行緒即Thread.currentThread() 下面先簡單模擬一個ThreadLocal

public class MyThreadLocal <T> {
    private Map<Thread, T> map = new HashMap<Thread, T>();

    public void set(T data) {
        // 使用當前執行緒做key
        map.put(Thread.currentThread(), data);
} public T get() { return map.get(Thread.currentThread()); } public void remove() { map.remove(Thread.currentThread()); } }

寫一個支援事務的dao,需要提供getconnection(),beginTransaction(),commitTransaction(),rollBackTransaction()的方法

使用該getTXConnection()調包之前DAO的CRUD 的getConnection()方法,並把connection 存放到ThreadLocal中


    public static Connection getTXConnection(){
        Connection connection = tl.get();
        if (connection==null){
            try {
                connection = dataSource.getConnection();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            tl.
set(connection); } return connection; }

beginTransaction開啟事務

    public static void beginTransaction() {
        Connection con = tl.get();
        if (con==null){
            try {
                con = dataSource.getConnection();
                con.setAutoCommit(false);
            } catch (SQLException e) {
                e.printStackTrace();
            }

            tl.set(con);
        }else{
            throw new  RuntimeException("你已經開啟事務了");
        }

    }

commitTransaction提交事務,關閉連線,移除ThreadLocal中的connection

    public static   void commitTransaction(){

        Connection con = tl.get();
        if (con==null){
            throw  new RuntimeException("你還沒有開啟事務");
        }else {
            try {
                con.commit();
                con.close();
                tl.remove();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

rollBackTransaction回滾事務,關閉連線,移除ThreadLocal中的connection

    public static void rollBackTransaction() {
        Connection con = tl.get();
        if (con==null){
            throw new RuntimeException("你還沒有開啟事務");
        }else {
            try {
                con.rollback();
                con.close();
                tl.remove();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }

對於close方法,對於事務而言,是不需要關閉的,關閉在commitTransaction和rollBackTransaction中,但為了相容沒有開啟事務的CRUD,這裡需要判斷


    public static void close(Connection con, PreparedStatement ps)  {

        if (ps != null) {
            try {
                ps.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        Connection connection = tl.get();
        //不是事務con
        if (connection==null){
            try {
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }else {
            //不是事務con
            if (con!=connection){
                try {
                    con.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        //事務的關閉con在commit和rollback中
    }

接下來是加強之前寫的DAO了,這裡只展示update方法

public class JDBCUtils {

    private static BasicDataSource dataSource;

    private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>();

    static {
        dataSource = new BasicDataSource();
        Properties properties = new Properties();
        InputStream in = JDBCUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
        try {
            properties.load(in);
            dataSource.setDriverClassName(properties.getProperty("driver"));
            dataSource.setUrl(properties.getProperty("jdbcUrl"));
            dataSource.setUsername(properties.getProperty("user"));
            dataSource.setPassword(properties.getProperty("password"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    //insert update delete
    public static void update(String sql,Object... args){
        Connection connection = getTXConnection();
        PreparedStatement ps=null;
        try {
            ps = connection.prepareStatement(sql,Statement);
            for (int i=0;i<args.length;i++){
                ps.setObject(i+1,args[i]);
            }
            ps.executeUpdate();
        }catch (Exception e){
            e.printStackTrace();
        }
        JDBCUtils.close(connection,ps);
    }
}