V 1.0(封装创建连接、回收连接)
public abstract class DruidToolsVersion1 {
private static DataSource ds;
static {
try {
Properties properties = new Properties();
File file = new File("cfg/driudsoft.properties");
FileInputStream fileInputStream = new FileInputStream(file);
properties.load(fileInputStream);
ds= DruidDataSourceFactory.createDataSource(properties);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static Connection getConnnextion() throws SQLException {
Connection connection = ds.getConnection();
return connection;
}
public static void collectConnection(Connection connection) throws SQLException {
connection.close();
}
}
Connection connnection = DruidToolsVersion1.getConnnection();
DruidToolsVersion1.collectConnection(connnextion);
V 2.0(同一个线程的不同方法获取同一个连接)
- 在转账事务的实现中,流程是:在srevice层统一创建驱动和连接,并把连接对象传递给加钱和减钱的方法,所以Dao层中的加减钱方法都传入了连接connection。因为在service、Dao层使用的连接都是同一个线程在调用,所以考虑能不能让二者都调用同一个线程,因此引入线程本地变量,在封装的工具类中创建一个ThreadLocal线程本地变量,在service层和Dao层调用封装的工具类创建连接,这样就可以保证service和Dao层是同样的连接。
- ThreadLocal用于保存某个线程共享变量,不同线程只能从中get,set,remove自己的变量,而不会影响其他线程的变量。get、set、remove用于获取、设置、移除ThreadLocal中当前线程共享变量的值。
public class DruidToolsVersion2 {
private static ThreadLocal<Connection> tl=new ThreadLocal<>();
private static DataSource ds;
static {
try {
Properties properties = new Properties();
File file = new File("cfg/druidsoft.properties");
FileInputStream fileInputStream = new FileInputStream(file);
properties.load(fileInputStream);
ds=DruidDataSourceFactory.createDataSource(properties);
}catch (Exception e){
throw new RuntimeException(e);
}
}
public static Connection getConnection() throws SQLException {
Connection connection = tl.get();
if(connection==null){
connection = ds.getConnection();
tl.set(connection);
}
return connection;
}
public static void collectConnection() throws SQLException {
Connection connection = tl.get();
if(connection!=null){
tl.remove();
connection.setAutoCommit(true);
connection.close();
}
}
}
在转账事务中的调用:
service层不用在创建驱动建立连接了,直接调用DruidToolsVersion2.getconnection()和DruidToolsVersion2.collectconnection()来建立连接和释放连接
Dao层也不用再传入connection变量了,直接调用DruidToolsVersion2.getconnection()获取连接