TheadLocal 얘기 좀 해요.

5413 단어
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&amp;useUnicode=true&amp;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);
            }
        }
    }
}

좋은 웹페이지 즐겨찾기