Spring事务是通过ThreadLocal类来实现,所以只有主线程有事务管理.

我通过自己写持久层代码,实现了多线程处理享受一个事务,一个线程报错所有线程回滚.但是真正能实现这个功能的还在研究中.希望有懂的大神,提供下思路!

@Service
public class TestServiceImpl2 implements TestService {
    @Autowired
    private TestMapper testMapper;
    @Autowired
    private DruidDataSource dr;

    @Override
    public List<Test> queryTest() {
        return testMapper.selectAllTest();
    }

    @Override
    public void go() throws SQLException  {
        // 创建数据连接
        final DruidPooledConnection conn = dr.getConnection();
        //创建线程屏障
        CyclicBarrier cyc = new CyclicBarrier(3);
        //创建固定线程池
        ExecutorService pool = Executors.newFixedThreadPool(2);
        //方法开始前系统时间
        long start = System.currentTimeMillis();
        final String sql = "insert into test(id,name)values(?,?)";
        try {
            // 关闭自动提交
            conn.setAutoCommit(false);

            // 第一个线程
            pool.execute(() -> {
                PreparedStatement prepareStatement = null;
                try {
                    prepareStatement = conn.prepareStatement(sql);
                    prepareStatement.setInt(1, 1);
                    prepareStatement.setString(2, "a");
                    Thread.sleep(6000);
                    int count = prepareStatement.executeUpdate();
                        cyc.await();
                } catch (SQLException | InterruptedException | BrokenBarrierException e) {
                    try {
                        if (null != conn) {
                            conn.close();
                        }
                        cyc.reset();
                    } catch (SQLException e1) {
                        e1.printStackTrace();
                    }
                    e.printStackTrace();
                } finally {
                    try {
                        if (null != prepareStatement) {
                            prepareStatement.close();
                        }
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }
            });

            // 第二个线程
            pool.execute(() -> {
                PreparedStatement prepareStatement = null;
                try {
                    prepareStatement = conn.prepareStatement(sql);
                    prepareStatement.setInt(1, 2);
                    prepareStatement.setString(2, "b");
                    Thread.sleep(5000);
                    int count = prepareStatement.executeUpdate();
                        cyc.await();
                } catch (SQLException | InterruptedException | BrokenBarrierException e) {
                    try {
                        if (null != conn) {
                            conn.close();
                        }
                        cyc.reset();
                    } catch (SQLException e1) {
                        e1.printStackTrace();
                    }
                    e.printStackTrace();
                } finally {
                    try {
                        if (null != prepareStatement) {
                            prepareStatement.close();
                        }
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }
            });

            cyc.await();
            long end = System.currentTimeMillis();
            System.out.println("总耗时="+(end-start));
            conn.commit();
        } catch (SQLException | InterruptedException | BrokenBarrierException e) {
            conn.rollback();
            e.printStackTrace();
        } finally {
            try {
                if (null != conn) {
                    conn.close();
                }
                pool.shutdown();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

这里只用到了spring的自动装配,得到了数据源.

看到了一个人写的,但是也没具体想到怎么实现,原文是:

最近做Performance Tuning, 有一个功能,在用户点击后要做两次数据库存储,而且还要发送好几条JMS message,造成反应极慢。所以我考虑用FutureTask来并发做几件事情,我在service层里新建FutureTask。写完后,测试发现除了还在原来主线程中的数据库操作外,其他数据库,message操作通通变成不受事务控制的了。
研究Spring源代码,发现原来Spring事务是通过ThreadLocal类来实现的,在TransactionSynchronizationManager中有两个方法:
public static void bindResource(Object key, Object value) throws IllegalStateException
public static Object getResource(Object key)
分别用来绑定和获得对应线程的事务控制实例。所以对于不同的线程,默认来说肯定会有不用的事务控制。我们的事务控制是通过aop加在service层上的,所以只有那个主线程才有事务,而后来创建的FutureTask由于没有经过AOP的代码,所以就没事务控制了。
问题:能把同一事务控制加到多个线程中吗?理论上是可以的,我们可以在创建线程前在主线程中通过getResource方法把对象获取出来,传入新创建的线程,让后用bindResource方法绑定上去。这样会有问题吗?上网查了下,发现还是有潜在问题的,因为数据库的操作,只支持单线程下保证事务正确,如果多个线程操作同一事务就会出问题,要保证不出错,就必须确保更新数据库的方法是同步的,也就是一次只能一个线程操作数据库(想想还是挺麻烦的,因为我们现在都用spring的template)。但是如果事务是JTA的呢,因为操作的是不同的数据库,或者数据库和JMS(我们的数据库操作和JMS不在同一事务中,以后有时间可以谈谈),是不是就可以同步操作呢?
我想应该是可以的吧,对于事务扩展到多个线程的问题,都是我的猜想,有空大家可以去试试。哪位如果认为我说的不对,欢迎指点!!

待改,记录一下:

package com.test.service;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledConnection;
import com.test.mapper.TestMapper;
import com.test.model.Test;

@Service
public class TestServiceImpl2 implements TestService {
    @Autowired
    private TestMapper testMapper;
    @Autowired
    private DruidDataSource data;



    @Override
    public List<Test> queryTest() {
        return null;
    }

    private static boolean flag = true;

    @Override
    public long go() {
        ExecutorService pool = Executors.newFixedThreadPool(2);

        long start = System.currentTimeMillis();

        DruidPooledConnection connection = null;
        try {
            connection = data.getConnection();
            CyclicBarrier cyc = new CyclicBarrier(3);
            String sql = "insert into test(id,name)values(?,?)";

            connection.setAutoCommit(false);

            pool.execute(new A(connection, sql, cyc));
            pool.execute(new B(connection, sql, cyc));

            cyc.await();

            connection.commit();

            long end = System.currentTimeMillis();
            return end - start;
        } catch (SQLException | InterruptedException | BrokenBarrierException e) {
            try {
                connection.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        } finally {
            try {
                if (null != connection) {
                    connection.close();
                }
                pool.shutdown();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return 0;
    }

}

class A implements Runnable {
    private DruidPooledConnection connection;
    private CyclicBarrier cyc;
    private String sql;

    public A(DruidPooledConnection connection, String sql, CyclicBarrier cc) {
        this.connection = connection;
        this.cyc = cc;
        this.sql = sql;
    }

    @Override
    public void run() {
        PreparedStatement prepareStatement = null;
        try {
            prepareStatement = connection.prepareStatement(sql);
            prepareStatement.setString(1, String.valueOf(UUID.randomUUID()).replaceAll("-", ""));
            prepareStatement.setString(2, "b");
            prepareStatement.executeUpdate();
            cyc.await();
        } catch (SQLException | InterruptedException | BrokenBarrierException e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != prepareStatement) {
                    prepareStatement.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

class B implements Runnable {
    private DruidPooledConnection connection;
    private CyclicBarrier cyc;
    private String sql;

    public B(DruidPooledConnection connection, String sql, CyclicBarrier cc) {
        this.connection = connection;
        this.cyc = cc;
        this.sql = sql;
    }

    @Override
    public void run() {
        PreparedStatement prepareStatement = null;
        try {
            prepareStatement = connection.prepareStatement(sql);
            prepareStatement.setString(1, String.valueOf(UUID.randomUUID()).replaceAll("-", ""));
            prepareStatement.setString(2, "a");
            prepareStatement.executeUpdate();
            cyc.await();
        } catch (SQLException | InterruptedException | BrokenBarrierException e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != prepareStatement) {
                    prepareStatement.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}