使用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();
        }            
        }
    }

         借了别人的,一定要还~~~

 

posted @ 2015-12-30 11:25  猪头强  阅读(6354)  评论(0编辑  收藏  举报