Idea和redis的坑


1: 直接在Idea里面,建TestNG的Test類時, 里面的多線程代碼,一直會提示報錯,沒有任何提示,直接就test任務結束。 解決方案:使用main建入口的方式進行測試,千萬不要使用testng的@Test注解這種方式進行測試。 原因,估計是多線程引起的。怎么弄還不明白,只能換成main方法里面去執行多線程。 坑2: 多線程並發會造成沖突,會報各種錯。 解決方法:使用JRedisPool建立線程池。 而且在操作時,使用synchronized把操作方法進行封裝。否則依然會報錯。 坑3: 超出線程池容量。1000個線程,會報大量的錯。 解決方法: JedisPoolConfig里面設置
//Redis服務器IP
    private static String ADDR_ARRAY = "127.0.0.1";

    //Redis的端口號
    private static int PORT = 6379;

    //訪問密碼
    private static String AUTH = "";

    //可用連接實例的最大數目,默認值為8;
    //如果賦值為-1,則表示不限制;如果pool已經分配了maxActive個jedis實例,則此時pool的狀態為exhausted(耗盡)。
    private static int MAX_ACTIVE = 500;

    //控制一個pool最多有多少個狀態為idle(空閑的)的jedis實例,默認值也是8。
    private static int MAX_IDLE = 100;

    //等待可用連接的最大時間,單位毫秒,默認值為-1,表示永不超時。如果超過等待時間,則直接拋出JedisConnectionException;
    private static int MAX_WAIT = 10 * 1000;

    private static int TIMEOUT = 10 * 1000;//超時時間

    //在borrow一個jedis實例時,是否提前進行validate操作;如果為true,則得到的jedis實例均是可用的;
    private static boolean TEST_ON_BORROW = true;

    private static JedisPool jedisPool = null;

    /**
     * 初始化Redis連接池
     */
    private static void initialPool() {
        try {
            JedisPoolConfig config = new JedisPoolConfig();
            config.setMaxTotal(MAX_ACTIVE);
            config.setMaxIdle(MAX_IDLE);
            config.setMaxWaitMillis(MAX_WAIT);

            config.setTestOnBorrow(TEST_ON_BORROW);//使用時進行掃描,確保都可用

            config.setTestWhileIdle(true);//Idle時進行連接掃描

            config.setTestOnReturn(true);//還回線程池時進行掃描
//
////表示idle object evitor兩次掃描之間要sleep的毫秒數
//            config.setTimeBetweenEvictionRunsMillis(30000);
//
////表示idle object evitor每次掃描的最多的對象數
//            config.setNumTestsPerEvictionRun(10);
//
////表示一個對象至少停留在idle狀態的最短時間,然后才能被idle object evitor掃描並驅逐;這一項只有在timeBetweenEvictionRunsMillis大於0時才有意義
//            config.setMinEvictableIdleTimeMillis(60000);

            if (StringUtils.isNotBlank(AUTH)) {
                jedisPool = new JedisPool(config, ADDR_ARRAY.split(",")[0], PORT, TIMEOUT, AUTH);
            } else {
                jedisPool = new JedisPool(config, ADDR_ARRAY.split(",")[0], PORT, TIMEOUT);
            }

        } catch (Exception e) {
            logger.error("First create JedisPool error : " + e);
            try {
                //如果第一個IP異常,則訪問第二個IP
                JedisPoolConfig config = new JedisPoolConfig();
                config.setMaxTotal(MAX_ACTIVE);
                config.setMaxIdle(MAX_IDLE);
                config.setMaxWaitMillis(MAX_WAIT);
                config.setTestOnBorrow(TEST_ON_BORROW);
                jedisPool = new JedisPool(config, ADDR_ARRAY.split(",")[1], PORT, TIMEOUT, AUTH);
            } catch (Exception e2) {
                logger.error("Second create JedisPool error : " + e2);
            }
        }
    }

    /**
     * 在多線程環境同步初始化
     */
    private static synchronized void poolInit() {
        if (jedisPool == null) {
            initialPool();
        }
    }


    /**
     * 同步獲取Jedis實例
     *
     * @return Jedis
     */
    public synchronized static Jedis getJedis() {
        if (jedisPool == null) {
            poolInit();
        }

        Jedis jedis = null;
        try {
            if (jedisPool != null) {
                jedis = jedisPool.getResource();
            }
        } catch (Exception e) {
            logger.error("Get jedis Error : " + e.getMessage(), e);
        } finally {
            returnResource(jedis);//歸還到Redis池里面
        }
        return jedis;
    }

    /**
     * 釋放jedis資源
     *
     * @param jedis
     */
    public static void returnResource(final Jedis jedis) {
        if (jedis != null && jedisPool != null) {
            jedisPool.returnResource(jedis);
        }
    }

    /**
     * 關閉連接池
     */
    public static void closePool() {
        if (jedisPool != null) {
            jedisPool.close();
        }
    }

    /**
     * 設置 String
     *
     * @param key
     * @param value
     */
    public synchronized static void setString(String key, String value) {
        try {
            value = StringUtils.isEmpty(value) ? "" : value;
            getJedis().set(key, value);
        } catch (Exception e) {
            logger.error("Set key error : " + e);
        }
    }

    /**
     * 設置 過期時間
     *
     * @param key
     * @param seconds 以秒為單位
     * @param value
     */
    public synchronized static void setString(String key, int seconds, String value) {
        try {
            value = StringUtils.isEmpty(value) ? "" : value;
            getJedis().setex(key, seconds, value);
        } catch (Exception e) {
            logger.error("Set keyex error : " + e);
        }
    }

    /**
     * 獲取String值
     *
     * @param key
     * @return value
     */
    public synchronized static String getString(String key) {
        if (getJedis() == null || !getJedis().exists(key)) {
            return null;
        }
        return getJedis().get(key);
    }

}

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM