zoukankan      html  css  js  c++  java
  • 使用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();
            }            
            }
        }

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

  • 相关阅读:
    第二周:Python3的内存管理
    第一周:JDBC中批量插入数据问题
    PyTorch对ResNet网络的实现解析
    三素数定理的证明及其方法(二)
    三素数定理的证明及其方法(一)
    羊车门问题
    对python语言学习的期待
    My first page
    windowns右键notepad++ 打开文件
    Idea里新建类的快捷键
  • 原文地址:https://www.cnblogs.com/qiangweikang/p/JedisPool.html
Copyright © 2011-2022 走看看