TheadLocal 얘기 좀 해요.
스레드의 측면에서 볼 때 목표 변수는 스레드의 로컬 변수와 같다. 이것도 클래스 이름에서'Local'이 표현하고자 하는 뜻이다.
사실 주로 말하고 싶은 것은 데이터베이스 연결의 역할이다. 바로 하나의 라인과 하나의 업무, 하나의session을 확보하는 것이다.요청 중의 한 업무는 여러 개의 DAO 작업과 관련되기 때문에 이러한 DAO의 연결성은 연결 탱크에서 얻을 수 없다. 연결 탱크에서 얻으면 두 개의 DAO가 두 개의 연결성을 사용하기 때문에 하나의 업무를 완성할 수 없다.DAO의 Connection이 ThreadLocal에서 Connection을 얻으면 이 DAO들은 같은 Connection에 포함됩니다.당연하죠. 그러면 DAO에서 커넥션을 끄면 안 되고, 끄면 다음 사용자가 사용할 수 없어요.
public class DataSourceFactory{
private static DataSource ds = null;
private static final ThreadLocal<Connection> threadLocal = new ThreadLocal<Connection>();
/**
* JNDI
* tomcat/conf/context.xml , :
* <Resource name="jdbc/forceviewDB" type="javax.sql.DataSource" username="forceview" password="forceview"
url="jdbc:postgresql://localhost/forceview?autoReconnect=true&useUnicode=true&characterEncoding=utf-8"
driverClassName="org.postgresql.Driver" maxIdle="3" maxWait="-1" maxActive="50"
validationQuery="select 1"
testOnBorrow="true"
testOnReturn="true"
testWhileIdle="true"
removeAbandoned="true"
removeAbandonedTimeout="180"
logAbandoned="true"
timeBetweenEvictionRunsMillis="180000"
minEvictableIdleTimeMillis = "180000"
/>
* jar
* @param jndi
*/
public static void init(String jndi) {
if(jndi==null||"".equals(jndi)){
jndi="java:/comp/env/jdbc/forceviewDB";
}
try {
Context initContext = new InitialContext();
ds = (DataSource) initContext.lookup(jndi);
} catch (Exception e) {
DhccLogger.error("", e);
}
}
/**
* spring ApplicationContext ds
* @param ctx
*/
public static void init(ApplicationContext ctx) {
try {
ds = (DataSource) ctx.getBean("dataSource");
} catch (RuntimeException e) {
DhccLogger.error("", e);
}
}
/**
* ds
* @param dataSource
*/
public static void init(DataSource dataSource) {
ds=dataSource;
}
/**
*
* threadLocal , ,
* , threadLocal
* @return
*/
public static Connection getConnection() {
Connection conn = threadLocal.get();
try {
if (conn == null || conn.isClosed()) {
conn = ds.getConnection();
threadLocal.set(conn);
}
} catch (Exception e) {
DhccLogger.error("", e);
}
return conn;
}
/**
*
* , , ,
* , , connection.close()
*/
public static void closeConnection() {
}
/**
* , ,
* ,
*/
public static void close() {
Connection conn = (Connection) threadLocal.get();
threadLocal.set(null);
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
DhccLogger.error("", e);
}
}
}
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.