Java 类redis.clients.jedis.Jedis 实例源码

项目:distributed-task-scheduler    文件:RedisDataCache.java   
/** {@inheritDoc} */
@Override
public Double zScore(String key, Object data) {
    int tries = 0;
    boolean sucess = false;
    Double retVal = null;
    do {
        tries++;
        try {
            Jedis jedis = pool.getResource();
            retVal = jedis.zscore(key, SerializationUtil.serialize(data));
            jedis.close();
            sucess = true;
        } catch (JedisConnectionException ex) {
            log.error(RedisConstants.CONN_FAILED_RETRY_MSG + tries);
            if (tries == numRetries) {
                throw ex;
            }
        }
    } while (!sucess && tries <= numRetries);
    return retVal;
}
项目:redis-client    文件:RedisClientImpl.java   
@Override
public <T> Map<String, T> hgetAllObjects(final String bizkey, final String nameSpace, final TypeReference<T> type,
        final GetDataCallBack<T> gbs) {
    final String key = CacheUtils.getKeyByNamespace(bizkey, nameSpace);
    return this.performFunction(key, new CallBack<Map<String, T>>() {
        public Map<String, T> invoke(Jedis jedis) {
            try {
                Map<String, String> all = jedis.hgetAll(key);
                Map<String, T> allObjs = new HashMap<String, T>();
                for (Entry<String, String> item : all.entrySet()) {
                    String _key = item.getKey();
                    T _value = CacheUtils.parseObject(key, item.getValue(), type);
                    allObjs.put(_key, _value);
                }
                return allObjs;
            } catch (Exception e) {
                logger.error("key:" + key + "hgetAllObjects Exception:" + e.getMessage());
            }
            return null;
        }
    });
}
项目:easyweb    文件:JedisUtils.java   
/**
 * 向List缓存中添加值
 * @param key 键
 * @param value 值
 * @return
 */
public static long listObjectAdd(String key, Object... value) {
    long result = 0;
    Jedis jedis = null;
    try {
        jedis = getResource();
        List<byte[]> list = Lists.newArrayList();
        for (Object o : value){
            list.add(toBytes(o));
        }
        result = jedis.rpush(getBytesKey(key), (byte[][])list.toArray());
        logger.debug("listObjectAdd {} = {}", key, value);
    } catch (Exception e) {
        logger.warn("listObjectAdd {} = {}", key, value, e);
    } finally {
        returnResource(jedis);
    }
    return result;
}
项目:webside    文件:RedisManager.java   
/**
 * 获取Set长度
 * @param setKey
 * @return
 */
public Long getLenBySet(String setKey) throws Exception {
    Jedis jds = null;
    try {
        jds = getJedis();
        jds.select(0);
        Long result = jds.scard(setKey);
        return result;
    } catch (Exception e) {
        throw e;
    } finally {
        if(jds != null)
        {
            jds.close();
        }
    }
}
项目:trioAop    文件:RedisStringOperationImpl.java   
@Override
public boolean expireat(String key, String val, int cacheTime) {
    Jedis jedis = getJedisPool().getResource();
    try {
        jedis.set(key, val);
        if (cacheTime > 0) {
            jedis.expire(key, cacheTime);
        }
        return true;
    } catch (Exception e) {
        logger.error("expireat ", e);
        return false;
    } finally {
        getJedisPool().returnResource(jedis);
    }
}
项目:JRediClients    文件:RedisService.java   
public String hget(String key, String field) {
    Jedis jedis = null;
    boolean success = true;
    String ret = null;
    try {
        jedis = jedisPool.getResource();
        if (jedis == null) {
            success = false;
            return ret;
        }
        ret = jedis.hget(key, field);
    } catch (Exception e) {
        success = false;
        returnBrokenResource(jedis, "hmgetString" + key, e);
    } finally {
        releaseReidsSource(success, jedis);
    }
    return ret;
}
项目:shuzheng    文件:UpmsSessionDao.java   
/**
 * 获取会话列表
 * @param offset
 * @param limit
 * @return
 */
public Map getActiveSessions(int offset, int limit) {
    Map sessions = new HashMap();
    Jedis jedis = RedisUtil.getJedis();
    // 获取在线会话总数
    long total = jedis.llen(ZHENG_UPMS_SERVER_SESSION_IDS);
    // 获取当前页会话详情
    List<String> ids = jedis.lrange(ZHENG_UPMS_SERVER_SESSION_IDS, offset, (offset + limit - 1));
    List<Session> rows = new ArrayList<>();
    for (String id : ids) {
        String session = RedisUtil.get(ZHENG_UPMS_SHIRO_SESSION_ID + "_" + id);
        // 过滤redis过期session
        if (null == session) {
            RedisUtil.lrem(ZHENG_UPMS_SERVER_SESSION_IDS, 1, id);
            total = total - 1;
            continue;
        }
         rows.add(SerializableUtil.deserialize(session));
    }
    jedis.close();
    sessions.put("total", total);
    sessions.put("rows", rows);
    return sessions;
}
项目:jspider    文件:RedisPriorityScheduler.java   
@Override
protected void pushWhenNoRepeat(Task task, Request request) {
    Jedis jedis = jedisPool.getResource();
    try {
        String content = serializer.serialize(request);
        if(request.getPriority() == 0) {
            jedis.rpush(RedisKeys.getQueueNoPriorityKey(task), content);
        } else if (request.getPriority() > 0) {
            jedis.zadd(RedisKeys.getZsetPlusPriorityKey(task), request.getPriority(), content);
        } else {
            jedis.zadd(RedisKeys.getZsetMinusPriorityKey(task), request.getPriority(), content);
        }

        jedis.sadd(RedisKeys.getSetKey(task), request.key());
    } finally {
        jedis.close();
    }
}
项目:SamaGamesAPI    文件:TeamSpeakAPI.java   
private static void publish(int id, String string)
{
    Jedis jedis = null;
    try
    {
        jedis = SamaGamesAPI.get().getBungeeResource();
        if (jedis != null)
            jedis.publish("tsbot", SamaGamesAPI.get().getServerName() + "/" + id + ":" + string);
    }
    catch (Exception exception)
    {
        SamaGamesAPI.get().getPlugin().getLogger().log(Level.SEVERE, "Jedis error", exception);
    }
    finally
    {
        if (jedis != null)
            jedis.close();
    }
}
项目:newblog    文件:JedisUtil.java   
public void zrem(String key, String member) {
    Jedis jedis = null;
    try {
        jedis = getJedis();
        if (jedis == null) {
            logger.error("get jedis fail");
        }
        jedis.zrem(key, member);
    } catch (JedisConnectionException e) {
        if (jedis != null) {
            jedis.close();
        }
    } finally {
        returnJedisResource(jedis);
    }
}
项目:JRediClients    文件:RedisService.java   
public String lpop(String key) {
    Jedis jedis = null;
    boolean success = true;
    String ret = null;
    try {
        jedis = jedisPool.getResource();
        if (jedis == null) {
            success = false;
            return ret;
        }
        ret = jedis.lpop(key);
    } catch (Exception e) {
        success = false;
        returnBrokenResource(jedis, "lpop key:" + key, e);
    } finally {
        releaseReidsSource(success, jedis);
    }
    return ret;
}
项目:redis_util    文件:CacheServiceRedisImpl.java   
public Long ttl(String key) {
    log.trace("get set expire " + key);
    Jedis jedis = null;
    try {
        jedis = redisConnection.getJedis();
        jedis.select(dbIndex);
        return jedis.ttl(key);
    } catch (Exception e) {
        log.warn(e.getMessage(), e);
    } finally {
        if (jedis != null) {
            jedis.close();
        }
    }
    return -2L;
}
项目:jodis-client    文件:RedisClientImpl.java   
/**
 * If key holds a hash, retrieve the value associated to the specified field.
 * <p>
 * If the field is not found or the key does not exist, a special 'nil' value is returned.
 * <p>
 * <b>Time complexity:</b> O(1)
 * 
 * @param key specified key
 * @param field hash field
 * @return Bulk reply
 */
@Override
public String hget(final String bizkey,final String nameSpace, final String field,final GetDataCallBack<String> gbs) {
    final String key = CacheUtils.getKeyByNamespace(bizkey,nameSpace);
    return this.performFunction(key, new CallBack<String>() {
        public String invoke(Jedis jedis) {
            String res = jedis.hget(key, field);
            if(StringUtils.isEmpty(res)){
                if(null!=gbs){
                    res = gbs.invoke();
                    if(StringUtils.isNotEmpty(res)){
                        hset(bizkey,nameSpace,field,res);
                    }
                }
            }
            return res;
        }
    });
}
项目:JRediSearch    文件:Client.java   
/**
 * Create the index definition in redis
 * @param schema a schema definition, see {@link Schema}
 * @param options index option flags, see {@link IndexOptions}
 * @return true if successful
 */
public boolean createIndex(Schema schema, IndexOptions options) {
    Jedis conn = _conn();

    ArrayList<String> args = new ArrayList<>();

    args.add(indexName);

    options.serializeRedisArgs(args);

    args.add("SCHEMA");

    for (Schema.Field f : schema.fields) {
        f.serializeRedisArgs(args);
    }

    String rep = conn.getClient()
            .sendCommand(commands.getCreateCommand(),
                         args.toArray(new String[args.size()]))
            .getStatusCodeReply();
    conn.close();
    return rep.equals("OK");

}
项目:ace-cache    文件:RedisServiceImpl.java   
@Override
public Long hlen(String key) {
    Jedis jedis = null;
    Long res = null;
    try {
        jedis = pool.getResource();
        res = jedis.hlen(key);
    } catch (Exception e) {

        LOGGER.error(e.getMessage());
    } finally {
        returnResource(pool, jedis);
    }
    return res;

}
项目:framework    文件:JedisUtils.java   
/**
 * 获取List缓存
 *
 * @param key 键
 * @return 值
 */
public static List<String> getList(String key) {
    List<String> value = null;
    Jedis jedis = null;
    try {
        jedis = getResource();
        if (jedis.exists(key)) {
            value = jedis.lrange(key, 0, -1);
            logger.debug("getList {} = {}", key, value);
        }
    } catch (Exception e) {
        logger.warn("getList {} = {}", key, value, e);
    } finally {
        returnResource(jedis);
    }
    return value;
}
项目:JRediClients    文件:JedisSentinelTest.java   
@Test
public void sentinelSet() {
  Jedis j = new Jedis(sentinel.getHost(), sentinel.getPort());

  try {
    Map<String, String> parameterMap = new HashMap<String, String>();
    parameterMap.put("down-after-milliseconds", String.valueOf(1234));
    parameterMap.put("parallel-syncs", String.valueOf(3));
    parameterMap.put("quorum", String.valueOf(2));
    j.sentinelSet(MASTER_NAME, parameterMap);

    List<Map<String, String>> masters = j.sentinelMasters();
    for (Map<String, String> master : masters) {
      if (master.get("name").equals(MASTER_NAME)) {
        assertEquals(1234, Integer.parseInt(master.get("down-after-milliseconds")));
        assertEquals(3, Integer.parseInt(master.get("parallel-syncs")));
        assertEquals(2, Integer.parseInt(master.get("quorum")));
      }
    }

    parameterMap.put("quorum", String.valueOf(1));
    j.sentinelSet(MASTER_NAME, parameterMap);
  } finally {
    j.close();
  }
}
项目:onolisa    文件:SpringRedisClientImpl.java   
/**
 * Set the the respective keys to the respective values. MSET will replace old values with new values, while
 * {@link #msetnx(String...) MSETNX} will not perform any operation at all even if just a single key already exists.
 * <p>
 * Because of this semantic MSETNX can be used in order to set different keys representing different fields of an
 * unique logic object in a way that ensures that either all the fields or none at all are set.
 * <p>
 * Both MSET and MSETNX are atomic operations. This means that for instance if the keys A and B are modified,
 * another client talking to Redis can either see the changes to both A and B at once, or no modification at all.
 * 
 * @see #msetnx(String...)
 * 
 * @param keyValues respective keys
 * @return Status code reply Basically +OK as MSET can't fail
 */
@Override
public String mset(final Map<String, String> keyValues) {
    if (isSharding()) {
        throw new RedisClientException(UNSUPPORT);
    }
    return this.performFunction("", new CallBack<String>() {
        /**
         * invoke
         * @param jedis jedis
         * @return invoke results
         */
        public String invoke(Jedis jedis) {
            return jedis.mset(CacheUtils.smapToArray(keyValues));
        }
    });
}
项目:newblog    文件:JedisUtil.java   
public void zadd(String key, double score, String member) {
    Jedis jedis = null;
    try {
        jedis = getJedis();
        if (jedis == null) {
            logger.error("get jedis fail");
        }
        jedis.zadd(key, score, member);
    } catch (JedisConnectionException e) {
        if (jedis != null) {
            jedis.close();
        }
    } finally {
        returnJedisResource(jedis);
    }
}
项目:JRediClients    文件:RedisService.java   
/**
 * 获取key的剩余时间
 * 
 * @param key
 * @return
 */
public long getKeyTTL(String key) {
    Jedis jedis = null;
    long ret = 0;
    // Set<String> keys = null;
    boolean success = true;
    try {
        jedis = jedisPool.getResource();
        if (jedis == null) {
            success = false;
            return ret;
        }
        ret = jedis.ttl(key);
    } catch (Exception e) {
        success = false;
        returnBrokenResource(jedis, "key ttl", e);
    } finally {
        releaseReidsSource(success, jedis);
    }
    return ret;
}
项目:tdl-seckill    文件:RedisUtil.java   
/**
 * 向有序集合添加元素
 *
 * @param key key
 * @param scoreMembers Map
 * @param seconds seconds
 */
public boolean zadd(String key, Map<String, Double> scoreMembers, int seconds) {
    Jedis jedis = null;
    try {
        jedis = getConnect();
        jedis.zadd(key, scoreMembers);
        if (seconds > 0) {
            jedis.expire(key, seconds);
        }
    } catch (Exception e) {
        logger.error("redis zadd data failed!", e);
        return false;
    } finally {
        close(jedis);
    }
    return true;
}
项目:JRediClients    文件:RedisService.java   
public boolean setString(String key, String value, int seconds) {
    Jedis jedis = null;
    boolean success = true;
    boolean ret = false;
    try {
        jedis = jedisPool.getResource();
        if (jedis == null) {
            success = false;
            return ret;
        }
        ret = (jedis.set(key, value) != null);
        if (seconds >= 0) {
            jedis.expire(key, seconds);
        }
    } catch (Exception e) {
        success = false;
        releaseBrokenReidsSource(jedis, key, "setString", e, true);
    } finally {
        releaseReidsSource(success, jedis);
    }
    return ret;
}
项目:redisson-benchmark    文件:ListAddBenchmark.java   
public static void main(String[] args) throws InterruptedException {
    Bench<JedisPool> bench = new JedisBench() {
        @Override
        public void executeOperation(String data, JedisPool benchInstance, int threadNumber, int iteration,
                MetricRegistry metrics) {
            Jedis jedis = benchInstance.getResource();

            Timer.Context time = metrics.timer("list").time();
            String key = "list_" + threadNumber;
            jedis.rpush(key, data);
            time.stop();

            jedis.close();
        }
    };

    Benchmark benchmark = new Benchmark(bench);
    benchmark.run(args);
}
项目:ace-cache    文件:RedisServiceImpl.java   
@Override
public Double zincrby(String key, double score, String member) {
    Jedis jedis = null;
    Double res = null;
    try {
        jedis = pool.getResource();
        res = jedis.zincrby(key, score, member);
    } catch (Exception e) {

        LOGGER.error(e.getMessage());
    } finally {
        returnResource(pool, jedis);
    }
    return res;
}
项目:logistimo-web-service    文件:RedisMemcacheService.java   
@Override
public void put(String cacheKey, Object obj, int expiry) {
  Jedis jedis = null;
  try {
    jedis = pool.getResource();
    jedis.setex(cacheKey.getBytes(), expiry, getBytes(obj));
    pool.returnResource(jedis);
  } catch (Exception e) {
    LOGGER.warn("Failed to put key in cache {0}", cacheKey, e);
    pool.returnBrokenResource(jedis);
  }
}
项目:x7    文件:JedisConnector_Cache3.java   
public void set(byte[] key, byte[] value){

    Jedis jedis = null;
    try{
        jedis = get();
        if (jedis == null)
            return;
        jedis.set(key,value);
        pool.returnResource(jedis);
    }catch(Exception e){
        pool.returnBrokenResource(jedis);
    }

}
项目:aaden-pay    文件:JedisLock.java   
/**
 * Acqurired lock release.
 */
public synchronized void release(Jedis jedis) {
    if (locked) {
        jedis.del(lockKey);
        locked = !locked;
    }
}
项目:CodeBroker    文件:CacheManager.java   
private void putRedisActorPath(String identify, String identifier, String areaManagerKey) {
    Jedis jedis = getJedis();

    MapStructure<String> mapStructure = RedisStrutureBuilder.ofMap(jedis, String.class).withNameSpace(nameSpace).build();
    Map<String, String> map = mapStructure.get(areaManagerKey);

    map.put(identify, identifier);
    if (jedis != null) {
        jedis.close();
    }
}
项目:JRediClients    文件:SSLJedisTest.java   
/**
 * Tests opening an SSL/TLS connection to redis with an empty certificate
 * trust store. This test should fail because there is no trust anchor for the
 * redis server certificate.
 * 
 * @throws Exception
 */
@Test
public void connectWithShardInfoAndEmptyTrustStore() throws Exception {

  final URI uri = URI.create("rediss://localhost:6390");
  final SSLSocketFactory sslSocketFactory = createTrustNoOneSslSocketFactory();

  JedisShardInfo shardInfo = new JedisShardInfo(uri, sslSocketFactory, null, null);
  shardInfo.setPassword("foobared");

  Jedis jedis = new Jedis(shardInfo);
  try {
    jedis.get("foo");
    Assert.fail("The code did not throw the expected JedisConnectionException.");
  } catch (JedisConnectionException e) {
    Assert.assertEquals("Unexpected first inner exception.",
        SSLException.class, e.getCause().getClass());
    Assert.assertEquals("Unexpected second inner exception.",
        RuntimeException.class, e.getCause().getCause().getClass());
    Assert.assertEquals("Unexpected third inner exception.",
        InvalidAlgorithmParameterException.class, e.getCause().getCause().getCause().getClass());
  }

  try {
    jedis.close();
  } catch (Throwable e1) {
    // Expected.
  }
}
项目:Building_Effective_Microservices    文件:MeetupDAOImpl.java   
@Override
public Observable<Set<String>> listByType(String typez){

    try (Jedis jedis = pool.getResource()) {

        Set<String> result = null;
        try{
            result = jedis.hkeys(typez);
            return Observable.just(result);
        }catch(JedisDataException jde){
            return Observable.just(new HashSet<>());
        }
    }
}
项目:redis-client    文件:RedisClientImpl.java   
/**
 * 获取指定索引的字符串
 * 
 * @param key
 *            键值
 * @param index
 *            索引
 * @return 指定索引的字符串
 */
@Override
public String lindex(final String bizkey, final String nameSpace, final long index) {
    final String key = CacheUtils.getKeyByNamespace(bizkey, nameSpace);
    return this.performFunction(key, new CallBack<String>() {
        public String invoke(Jedis jedis) {
            return jedis.lindex(key, index);
        }
    });
}
项目:jodis-client    文件:RedisClientImpl.java   
@Override
public List<String> mget(String[] bizkeys,String nameSpace) {
    final String[] key = CacheUtils.getKeyByNamespace(bizkeys,nameSpace);
       return this.performFunction("", new CallBack<List<String>>() {
           public List<String> invoke(Jedis jedis) {
               return jedis.mget(key);
           }
       });
}
项目:easyweb    文件:JedisUtils.java   
/**
     * 获取资源
     * @return
     * @throws JedisException
     */
    public static Jedis getResource() throws JedisException {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
//          logger.debug("getResource.", jedis);
        } catch (JedisException e) {
            logger.warn("getResource.", e);
            returnBrokenResource(jedis);
            throw e;
        }
        return jedis;
    }
项目:jodis-client    文件:RedisClientImpl.java   
/**
 * setrange
 * 
 * @param key specified key
 * @param offset offset
 * @param value string value
 * @return result
 * 
 */
@Override
public Long setrange(final String bizkey,final String nameSpace, final long offset, final String value) {
    final String key = CacheUtils.getKeyByNamespace(bizkey,nameSpace);
    return this.performFunction(key, new CallBack<Long>() {
        public Long invoke(Jedis jedis) {
            return jedis.setrange(key, offset, value);
        }
    });
}
项目:smart-cache    文件:JedisOperator.java   
public Long setnx(final String key, final String value) {
    return execute(new JedisExecutor<Long>() {
        @Override
        Long doInJedis(Jedis jedis) {
            return jedis.setnx(key, value);
        }
    });
}
项目:azeroth    文件:JedisSentinelProvider.java   
public void release() {
    Jedis jedis = context.get();
    if (jedis != null) {
        context.remove();
        jedis.close();
        if (logger.isTraceEnabled()) {
            logger.trace("<<release a redis conn[{}]", jedis.toString());
        }
    }
}
项目:LazyREST    文件:JedisClientImpl.java   
public long ttl(String key) {
    Jedis jedis = jedisPool.getResource();
    Long result = null;
    try {
        result = jedis.ttl(key);
    } catch (Exception e) {
        jedisPool.returnBrokenResource(jedis);
    } finally {
        jedisPool.returnResource(jedis);
    }
    return result;
}
项目:xmall    文件:JedisClientPool.java   
@Override
public String get(String key) {
    Jedis jedis = jedisPool.getResource();
    String result = jedis.get(key);
    jedis.close();
    return result;
}
项目:jspider    文件:RedisScheduler.java   
@Override
public Request doPoll(Task task) {
    Jedis jedis = jedisPool.getResource();
    try {
        return serializer.deserialize(jedis.lpop(RedisKeys.getQueueKey(task)));
    } finally {
        jedis.close();
    }
}
项目:JInsight    文件:JedisPoolInstrumentationTest.java   
@Test
public void testReturnBrokenResource() throws Exception {
  Jedis jedis = pool.getResource();

  Snapshot getSnapshot = getTracker.snapshot();
  Snapshot relSnapshot = releaseTracker.snapshot();
  relSnapshot.increment();
  pool.returnBrokenResource(jedis);
  relSnapshot.validate();
  getSnapshot.validate();
}