jedis工具類—優化

jedis工具類的使用很簡單。但是考慮到一些性能的問題做出一些調整。


public Jedis getJedis() {
    Jedis jedis = null;
    try {
        jedis = jedisPool.getResource();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return jedis;
}
//隨便在放個使用的方法。
public Object get(String key){
    Jedis jedis=null;
    Object o=null;
    try{
        jedis=getJedis();
        if(null != jedis)
            o=SerializeUtil.unserialize(jedis.get(key));
    }catch(Exception e){
    }finally{
        returnResource(jedis);
    }
}
//這樣的話,假設一個service調用了3次redis,那麼就會去獲取jedis,還jedis。
//這樣就會導致非常的消耗資源
//也做了許多相同的事情。因此考慮換個方式。採用ThreadLocal來作爲jedis的保存。
//再加上在service層採用aop的方式,獲取jedis,再關閉jedis連接。
public static ThreadLocal<Jedis> jedisTL=new ThreadLocal<>();
 
public Jedis getJedis(){
    Jedis jedis=null;
    try{
        jedis=jedisTL.get();
        if(null == jedis){
            jedis=jedisPool.getResource();
            jedisTL.set(jedis);
        }
    }catch(Exception e){
    }
}
private void returnResource(Jedis jedis){
    try{
        if(null != jedis)
            jedisPool.returnResource(jedis);
    }catch(Exception e){}
}
 
通過AOP去threadLocal去獲取,沒有的話,就不去池裏面取了。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章