1. 程式人生 > >使用Redis搶紅包高併發出現connection refused的解決方案

使用Redis搶紅包高併發出現connection refused的解決方案

最近使用redis佇列實現搶紅包,在使用jmeter測試時發現1000個執行緒0s併發搶紅包出現connect refused錯誤,但是500個10s就正常。原始碼如下

	private static void initialPool() {
        try {
        	JedisPoolConfig config = new JedisPoolConfig();
    		config.setMaxActive(1024);
    		config.setMaxIdle(200);
    		config.setMaxWait(10000);
    		config.setTestOnBorrow(false);
    		pool = new JedisPool(config, IP, PORT, 10000);
        } catch (Exception e) {
            logger.error("create JedisPool error : " + e);
        }
	}
	
	private static synchronized void poolInit() {
        if (pool == null) {  
            initialPool();
        }
    }

	public synchronized static Jedis getJedis() {  
        if (pool == null) {  
            poolInit();
        }
        Jedis jedis = null;
        try {  
            if (pool != null) {  
                jedis = pool.getResource(); 
            }
        } catch (Exception e) {  
            logger.error("Get jedis error : " + e);
        } finally {
            returnResource(jedis);
        }
        return jedis;
    }
	
	public static void returnResource(final Jedis jedis) {
        if (jedis != null && pool !=null) {
        	pool.returnResource(jedis);
        }
    }

寫了一段程式碼1000個執行緒測試了一下jedis物件,發現獲取的都是同一個物件,檢視程式碼後發現是finally程式碼段釋放連線過早的問題導致的,把這段登出,在業務程式碼中使用完畢後釋放,這樣每次獲取的jedis物件就不一樣了。

再次使用jedis測試,1000個0s瞬間完成,無報錯