無奈自己寫了一個簡單的JDBC查詢緩存,分享一下

正在做一個項目,因爲不是一個人做的,所以很多地方還得用最原始的JDBC技術,享受不了Hibernate的查詢緩存,,而且我們用的是Oracle 10G,NND上網查,人家MySQL早就有查詢緩存了,Oracle非得11G才支持,無奈自己寫了一個簡單的基於SQL語句和CachedRowSet名值對的查詢緩存。測試了一下性能還不錯,大概10:1(其實這是廢話,從內存裏讀當然要比從數據庫中查詢快了)。

因爲簡單,沒有過多考慮清除緩存的策略,簡單地只要有修改就清空緩存。所以應用場合有兩個限制:
1、SQL語句的可能性不能無限多(例如如果語句中包含可變的時間日期就不行);
2、讀操作遠遠多於寫操作。

我用在權限管理中,肯定是很合適的。

下面是代碼:

[code=Java]package oas.common.cache;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.logging.Logger;

/**
 * 通用緩存類
 * @author shajunxing
 */
public class Cache<T> {

    private final static Logger logger = Logger.getLogger(Cache.class.getName());
    /**
     * 緩存
     */
    private Map<String, T> cache;
    /**
     * 訪問計數器
     */
    private long visitedCount;
    /**
     * 命中計數器
     */
    private long hitCount;

    /**
     * 構造函數
     * @param maxSize 緩存最大容量
     */
    public Cache(final int maxSize) {
        cache = new LinkedHashMap<String, T>(1, 0.75F, true) {

            @Override
            protected boolean removeEldestEntry(Entry<String, T> eldest) {
                return size() > maxSize;
            }
        };
        clear();
    }

    /**
     * 取出一個值
     * @param key 鍵
     * @return 值/空
     */
    public T get(String key) {
        if (key == null) {
            return null;
        }

        visitedCount++;
        if (cache.containsKey(key)) {
            hitCount++;
            return cache.get(key);
        } else {
            return null;
        }
    }

    /**
     * 存入一個值
     * @param key 鍵
     * @param value 值
     */
    public synchronized void put(String key, T value) {
        if ((key == null) || (value == null)) {
            return;
        }

        cache.put(key, value);
    }

    /**
     * 清除緩存,復位計數器
     */
    public void clear() {
        cache.clear();
        visitedCount = 0;
        hitCount = 0;
    }

    /**
     * 獲取命中計數
     * @return 命中計數
     */
    public long getHitCount() {
        return hitCount;
    }

    /**
     * 獲取訪問計數
     * @return 訪問計數
     */
    public long getVisitedCount() {
        return visitedCount;
    }

    /**
     * 執行一個任務,如果在緩存中有對應的值,那麼直接返回,否則執行任務並把輸出保存入緩存
     * @param task 任務
     * @return 任務返回值
     */
    public T doCachedTask(CachedTask<T> task) {
        String key = task.getKey();
        T value = get(key);
        if (value == null) {
            value = task.run();
            put(key, value);
        }
        return value;
    }

    /**
     * 返回緩存內容
     * @return 緩存內容
     */
    @Override
    public String toString() {
        StringBuilder str = new StringBuilder("/n");
        for (Map.Entry<String, T> entry : cache.entrySet()) {
            str.append("Key: " + entry.getKey() + "/n");
            str.append("Value: " + entry.getValue() + "/n");
        }
        return str.toString();
    }
}
[/code]

[code=Java]package oas.common.cache;

/**
 * 通用緩存任務類,執行一個簡單的緩存任務
 * @author shajunxing
 */
public abstract class CachedTask<T> {

    private String key;

    public String getKey() {
        return key;
    }

    public CachedTask(String key) {
        this.key = key;
    }

    public abstract T run();
}
[/code]

[code=Java]package oas.common;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
import javax.sql.rowset.CachedRowSet;
import oas.common.cache.Cache;
import oas.common.cache.CachedTask;

/**
 * JDBC助手類
 * @author shajunxing
 */
public class JdbcHelper {

    private final static Logger logger = Logger.getLogger(JdbcHelper.class.getName());
    private static ComboPooledDataSource cpds;
    private static ThreadLocal<Connection> threadLocal = null;
    private static Cache<CachedRowSet> queryCache = new Cache<CachedRowSet>(10000);


    static {
        try {
            Class.forName(Utility.getProperty("hibernate.connection.driver_class"));
            // 初始化C3P0
            cpds = new ComboPooledDataSource();
            cpds.setDriverClass(Utility.getProperty("hibernate.connection.driver_class"));
            cpds.setJdbcUrl(Utility.getProperty("hibernate.connection.url"));
            cpds.setUser(Utility.getProperty("hibernate.connection.username"));
            cpds.setPassword(Utility.getProperty("hibernate.connection.password"));
            logger.info("連接池大小:" + cpds.getMaxPoolSize());
            cpds.setMaxPoolSize(100);
            cpds.setMaxStatements(10);
            // 初始化線程局部變量
            threadLocal = new ThreadLocal<Connection>();
        } catch (ClassNotFoundException ex) {
            logger.severe("JDBC驅動加載失敗:" + ex);
            cpds = null;
            System.exit(-1);
        } catch (PropertyVetoException ex) {
            logger.severe("C3P0初始化失敗:" + ex);
            cpds = null;
            System.exit(-1);
        }
    }

    /**
     * 獲取連接
     * @return 可用的連接
     * @throws java.sql.SQLException
     */
    public static Connection getConnection() throws SQLException {
        Connection conn = threadLocal.get();
        if (conn == null) {
            conn = cpds.getConnection();
//            conn = DriverManager.getConnection(
//                    Utility.getProperty("hibernate.connection.url"),
//                    Utility.getProperty("hibernate.connection.username"),
//                    Utility.getProperty("hibernate.connection.password"));
            conn.setAutoCommit(false);
            threadLocal.set(conn);
        }
        return conn;
    }

    /**
     * 關閉連接
     * @param conn 連接
     */
    public static void closeConnection() {
        Connection conn = threadLocal.get();
        threadLocal.set(null);
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException ex) {
                logger.severe("關閉Connection失敗:" + ex);
            }
        }
    }

    /**
     * 提交事務
     * @throws java.sql.SQLException
     */
    public static void commit() throws SQLException {
        getConnection().commit();
    }

    /**
     * 回滾事務
     */
    public static void rollback() {
        try {
            getConnection().rollback();
        } catch (SQLException ex) {
            logger.severe("事務回滾異常:" + ex);
        }
    }

    /**
     * 關閉聲明
     * @param stmt 聲明
     */
    public static void close(Statement stmt) {
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException ex) {
                logger.severe("關閉Statement失敗:" + ex);
            }
        }
    }

    /**
     * 關閉結果集
     * @param rs 結果集
     */
    public static void close(ResultSet rs) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException ex) {
                logger.severe("關閉ResultSet失敗:" + ex);
            }
        }
    }

    /**
     * 獲取一個緩存行集對象
     * @return 緩存行集對象
     */
    private static CachedRowSet getCachedRowSet() {
        CachedRowSet ret = null;
        try {
            ret = (CachedRowSet) Class.forName("com.sun.rowset.CachedRowSetImpl").newInstance();
        } catch (InstantiationException ex) {
            logger.severe(ex.toString());
        } catch (IllegalAccessException ex) {
            logger.severe(ex.toString());
        } finally {
            return ret;
        }
    }

    /**
     * 查詢
     * @param sql SQL語句
     * @return 查詢結果
     */
    public static CachedRowSet query(String sql) {
        CachedRowSet crs = getCachedRowSet();
        if (crs == null) {
            return null;
        }

        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        try {
            conn = getConnection();
            stmt = conn.createStatement();
            rs = stmt.executeQuery(sql);
            crs.populate(rs);
            return crs;
        } catch (SQLException ex) {
            logger.severe(ex.toString());
            return null;
        } finally {
            close(rs);
            close(stmt);
            closeConnection();
        }
    }

    /**
     * 緩存查詢
     * @param sql SQL語句
     * @return 查詢結果
     */
    public static CachedRowSet cachedQuery(final String sql) {
        return queryCache.doCachedTask(new CachedTask<CachedRowSet>(sql) {

            @Override
            public CachedRowSet run() {
                return query(sql);
            }
        });
    }

    public static void clearCache() {
        queryCache.clear();
    }

    public static long getCacheHitCount() {
        return queryCache.getHitCount();
    }

    public static long getCacheVisitedCount() {
        return queryCache.getVisitedCount();
    }

    public static void main(String[] args) throws SQLException {
        for (int i = 0; i < 1000; i++) {
            Thread th = new Thread(new Runnable() {

                @Override
                public void run() {
                    CachedRowSet rs = JdbcHelper.query("select classid from mta_class order by classid");
                    if (rs != null) {
                        try {
                            List<String> ids = new ArrayList<String>();
                            while (rs.next()) {
                                ids.add(rs.getString("classid"));
                            }
                            logger.info(ids.toString());
                        } catch (SQLException ex) {
                            logger.severe(ex.toString());
                        }
                    }
                }
            });
            th.start();
        }
    }
}
[/code]

發佈了58 篇原創文章 · 獲贊 2 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章