使用jedis2.8.0連接redis


   下載了最新的jedis客戶端jedis2.8.0,在網上找了找jedis使用連接池的工具類,拿來發現都是低版本的jedis寫法:

    returnResource();

    returnBrokenResource();

    這倆方法過期了~,查不到最新版本的寫法,裝逼未遂~~  

    於是去看了看源碼,發現源碼的注釋寫的很清楚:

/**
   * @deprecated starting from Jedis 3.0 this method will not be exposed.
   * Resource cleanup should be done using @see {@link redis.clients.jedis.Jedis#close()}
   */
  @Override
  @Deprecated
  public void returnResource(final Jedis resource) {
    if (resource != null) {
      try {
        resource.resetState();
        returnResourceObject(resource);
      } catch (Exception e) {
        returnBrokenResource(resource);
        throw new JedisException("Could not return the resource to the pool", e);
      }
    }
  }

用close()方法就可以了,跟蹤看看close()方法:

@Override
  public void close() {
    if (dataSource != null) {
      if (client.isBroken()) {
        this.dataSource.returnBrokenResource(this);
      } else {
        this.dataSource.returnResource(this);
      }
    } else {
      client.close();
    }
  }

dataSource 為定義的連接池 ,如果連接池不為空,做一些歸還連接的操作,jedis的連接池設計都是基於org.apache.commons.pool2,這倆方法沒跟着看,不過就是將連接的屬性值改為了可用之類的。

如果連接池為空的話,直接斷開與redis服務的連接啦~

 

所以在寫一些基礎類的時候,看起來應該是這樣的:

public <T> void set(T item) {
        Jedis jedis =null;
        try {
            jedis = JedisClient.getJedis();
            String v = cacheKeyUtil.getDefaultKey(item);
            jedis.set(v, iserializer.serialize(item));
        } catch (Exception e) {
            logger.warn("set", item, e);
        } finally {
      if(null != jsdis){
    jedis.close();
        }            
        }
    }

         借了別人的,一定要還~~~

 


免責聲明!

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



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