redis.clients.jedis.Jedis Java Examples

The following examples show how to use redis.clients.jedis.Jedis. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JedisPoolDemo.java    From Redis-4.x-Cookbook with MIT License 6 votes vote down vote up
public static void main(String[] args) {
    //Creating a JedisPool of Jedis connections to localhost Redis server
    JedisPool jedisPool = new JedisPool(new JedisPoolConfig(), "localhost");

    //Get a Jedis connection from pool
    try (Jedis jedis = jedisPool.getResource()) {
        String restaurantName = "Kyoto Ramen";
        Map<String, String> restaurantInfo = new HashMap<>();
        restaurantInfo.put("address", "801 Mission St, San Jose, CA");
        restaurantInfo.put("phone", "555-123-6543");
        jedis.hmset(restaurantName, restaurantInfo);
        jedis.hset(restaurantName, "rating", "5.0");
        String rating = jedis.hget(restaurantName, "rating");
        System.out.printf("%s rating: %s\n", restaurantName, rating);
        //Print out hash
        for (Map.Entry<String, String> entry: jedis.hgetAll(restaurantName).entrySet()) {
            System.out.printf("%s: %s\n", entry.getKey(), entry.getValue());
        }
    }
    System.exit(0);
}
 
Example #2
Source File: JedisUtils.java    From Shop-for-JavaWeb with MIT License 6 votes vote down vote up
/**
 * 设置Map缓存
 * @param key 键
 * @param value 值
 * @param cacheSeconds 超时时间,0为不超时
 * @return
 */
public static String setMap(String key, Map<String, String> value, int cacheSeconds) {
	String result = null;
	Jedis jedis = null;
	try {
		jedis = getResource();
		if (jedis.exists(key)) {
			jedis.del(key);
		}
		result = jedis.hmset(key, value);
		if (cacheSeconds != 0) {
			jedis.expire(key, cacheSeconds);
		}
		logger.debug("setMap {} = {}", key, value);
	} catch (Exception e) {
		logger.warn("setMap {} = {}", key, value, e);
	} finally {
		returnResource(jedis);
	}
	return result;
}
 
Example #3
Source File: RedisClient.java    From apollo with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Remove the specified keys.
 *
 * @param key
 *
 * @return false if redis did not execute the option
 */
public boolean delete(String key) {
    Jedis jedis = null;
    try {
        jedis = this.jedisPool.getResource();
        jedis.del(SafeEncoder.encode(key));
        logger.info("delete key:" + key);

        return true;
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        this.jedisPool.returnBrokenResource(jedis);
    } finally {
        if (jedis != null) {
            this.jedisPool.returnResource(jedis);
        }
    }
    return false;
}
 
Example #4
Source File: RedisLockInternals.java    From Distributed-Kit with Apache License 2.0 6 votes vote down vote up
private String createRedisKey(String lockId) {
    Jedis jedis = null;
    boolean broken = false;
    try {
        String value=lockId+randomId(1);
        jedis = jedisPool.getResource();
        String luaScript = ""
                + "\nlocal r = tonumber(redis.call('SETNX', KEYS[1],ARGV[1]));"
                + "\nredis.call('PEXPIRE',KEYS[1],ARGV[2]);"
                + "\nreturn r";
        List<String> keys = new ArrayList<String>();
        keys.add(lockId);
        List<String> args = new ArrayList<String>();
        args.add(value);
        args.add(lockTimeout+"");
        Long ret = (Long) jedis.eval(luaScript, keys, args);
        if( new Long(1).equals(ret)){
            return value;
        }
    }finally {
        if(jedis!=null) jedis.close();
    }
    return null;
}
 
Example #5
Source File: DistributedJobBean.java    From rebuild with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 是否可安全运行,即并发判断
 * @return
 */
protected boolean isSafe() {
    if (Application.rbvMode() && Application.getCommonCache().isUseRedis()) {
        JedisPool pool = Application.getCommonCache().getJedisPool();
        String jobKey = getClass().getName() + LOCK_KEY;

        try (Jedis jedis = pool.getResource()) {
            String tryLock = jedis.set(jobKey, LOCK_KEY, SET_IF_NOT_EXIST, SET_WITH_EXPIRE_TIME, LOCK_TIME);
            if (tryLock == null) {
                LOG.info("The job has been executed by another instance");
                return false;
            }
        }
    }
    return true;
}
 
Example #6
Source File: RGTRedisService.java    From redis-game-transaction with Apache License 2.0 6 votes vote down vote up
/**
 * 设置
 * @param key
 * @param value
 * @return
 */
@Override
public boolean setNxString(String key, String value, int seconds) throws Exception{
    Jedis jedis = null;
    boolean success = true;
    boolean result = false;
    try {
        jedis = jedisPool.getResource();
        result = (jedis.setnx(key, value) != 0);
        if(seconds > -1){
            jedis.expire(key, seconds);
        }
    } catch (Exception e) {
        success = false;
        releasBrokenReidsSource(jedis, key, "setNxString", e, false);
        throw e;
    } finally {
        releaseReidsSource(success, jedis);
    }

    return result;

}
 
Example #7
Source File: WispKvStoreCodisKvImpl.java    From wisp with Apache License 2.0 6 votes vote down vote up
/**
 * @param tableId
 * @param key
 * @param value
 *
 * @throws WispProcessorException
 */
@Override
public void put(String tableId, String key, String value) throws WispProcessorException {

    Jedis jedis = null;
    try {

        jedis = jedisPool.getResource();

        String hKey = redisPrefix + tableId;
        jedis.hset(hKey, key, value);

    } catch (Exception e) {

        throw new WispProcessorException(e);
    } finally {

        if (jedis != null) {
            jedis.close();
        }
    }

}
 
Example #8
Source File: RedisClient.java    From apollo with GNU General Public License v2.0 6 votes vote down vote up
public Object hget(String key, String field) {
    Jedis jedis = null;
    try {
        jedis = this.jedisPool.getResource();
        byte[] value = jedis.hget(SafeEncoder.encode(key), SafeEncoder.encode(field));
        logger.info("hget key:" + key + " field:" + field);

        return deserialize(value);
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        this.jedisPool.returnBrokenResource(jedis);
    } finally {
        if (jedis != null) {
            this.jedisPool.returnResource(jedis);
        }
    }
    return null;
}
 
Example #9
Source File: RedisAuthenticationIntegrationTest.java    From dyno with Apache License 2.0 6 votes vote down vote up
@Test
public void testJedisConnFactory_noAuthSuccess() throws Exception {
    redisServer = new RedisServer(REDIS_PORT);
    redisServer.start();

    Host noAuthHost = new HostBuilder().setHostname("localhost").setPort(REDIS_PORT).setRack(REDIS_RACK).setStatus(Status.Up).createHost();

    JedisConnectionFactory conFactory =
            new JedisConnectionFactory(new DynoOPMonitor("some-application-name"), null);
    ConnectionPoolConfiguration cpConfig = new ConnectionPoolConfigurationImpl("some-name");
    CountingConnectionPoolMonitor poolMonitor = new CountingConnectionPoolMonitor();
    HostConnectionPool<Jedis> hostConnectionPool =
            new HostConnectionPoolImpl<>(noAuthHost, conFactory, cpConfig, poolMonitor);
    Connection<Jedis> connection = conFactory
            .createConnection(hostConnectionPool);

    connection.execPing();
}
 
Example #10
Source File: SeckillServiceImpl.java    From jseckill with Apache License 2.0 6 votes vote down vote up
/**
 *
 * @param seckillId
 * @param userPhone
 * @return 0: 排队中; 1: 秒杀成功; 2: 秒杀失败
 */
@Override
public int isGrab(long seckillId, long userPhone) {
    int result = 0 ;

    Jedis jedis = jedisPool.getResource();
    try {
        String boughtKey = RedisKeyPrefix.BOUGHT_USERS + seckillId;
        result = jedis.sismember(boughtKey, String.valueOf(userPhone)) ? 1 : 0;
    } catch (Exception ex) {
        logger.error(ex.getMessage(), ex);
        result = 0;
    }

    if (result == 0) {
        if (!jedis.sismember(RedisKey.QUEUE_PRE_SECKILL, seckillId + "@" + userPhone)) {
            result =2;
        }
    }
    return result;
}
 
Example #11
Source File: RedisContainer.java    From bahir-flink with Apache License 2.0 6 votes vote down vote up
@Override
public void decrByEx(String key, Long value, Integer ttl) {
    Jedis jedis = null;
    try {
        jedis = getInstance();
        jedis.decrBy(key, value);
        if (ttl != null) {
            jedis.expire(key, ttl);
        }
    } catch (Exception e) {
        if (LOG.isErrorEnabled()) {
            LOG.error("Cannot send Redis with decrBy command with decrement {}  with ttl {} error message {}",
                    key, value, ttl, e.getMessage());
        }
        throw e;
    } finally {
        releaseInstance(jedis);
    }
}
 
Example #12
Source File: RedisJobStore.java    From redis-quartz with MIT License 5 votes vote down vote up
@Override
public int getNumberOfTriggers() throws JobPersistenceException {
     try (Jedis jedis = pool.getResource()) {
        lockPool.acquire();
		return jedis.scard(TRIGGERS_SET).intValue();
	} catch (Exception ex) {
		log.error("could not get number of triggers", ex);
		throw new JobPersistenceException(ex.getMessage(), ex.getCause());
	} finally {
        lockPool.release();
	}
}
 
Example #13
Source File: ZSetOperUtil.java    From springboot-learn with MIT License 5 votes vote down vote up
public static void oper(Jedis jedis) {

        jedis.zadd("zset", 3, "3");
        jedis.zadd("zset", 4, "5");
        jedis.zadd("zset", 5, "5");
        jedis.zadd("zset", 6, "6");
        Set<String> zset = jedis.zrange("zset", 0, -1);
        System.out.println("zset:" + zset);
        System.out.println("zset type:" + jedis.type("zset"));

    }
 
Example #14
Source File: JedisOperator.java    From smart-cache with Apache License 2.0 5 votes vote down vote up
public Set<byte[]> keys(final byte[] pattern) {
    return execute(new JedisExecutor<Set<byte[]>>() {
        @Override
        Set<byte[]> doInJedis(Jedis jedis) {
            return jedis.keys(pattern);
        }
    });
}
 
Example #15
Source File: JedisClientSingle.java    From learning-taotaoMall with MIT License 5 votes vote down vote up
@Override
public String hget(String hkey, String key) {
	Jedis jedis = jedisPool.getResource();
	String string = jedis.hget(hkey, key);
	jedis.close();
	return string;
}
 
Example #16
Source File: EnhancedJedisCluster.java    From super-cloudops with Apache License 2.0 5 votes vote down vote up
@Override
public Long sadd(final String key, final String... member) {
	checkArgumentsSpecification(key);
	return new EnhancedJedisClusterCommand<Long>(connectionHandler, maxAttempts) {
		@Override
		public Long doExecute(Jedis connection) {
			return connection.sadd(key, member);
		}
	}.run(key);
}
 
Example #17
Source File: RedisClient.java    From Mykit with Apache License 2.0 5 votes vote down vote up
public long incr(String key) {
	Jedis client = jedisPool.getResource();
	try {
		return client.incr(key);
	} finally {
		// 向连接池“归还”资源
		jedisPool.returnResourceObject(client);
	}
}
 
Example #18
Source File: JedisOperator.java    From smart-cache with Apache License 2.0 5 votes vote down vote up
public Boolean sismember(final byte[] key, final byte[] member) {
    return execute(new JedisExecutor<Boolean>() {
        @Override
        Boolean doInJedis(Jedis jedis) {
            return jedis.sismember(key, member);
        }
    });
}
 
Example #19
Source File: DistributedLock.java    From MicroCommunity with Apache License 2.0 5 votes vote down vote up
/**
 * 尝试获取分布式锁
 *
 * @param lockKey    锁
 * @param requestId  请求标识
 * @param expireTime 超期时间
 * @return 是否获取成功
 */
private static boolean tryGetDistributedLock(Jedis redis, String lockKey, String requestId, int expireTime) {
    String result = redis.set(lockKey, requestId, SET_IF_NOT_EXIST, SET_WITH_EXPIRE_TIME, expireTime);

    if (LOCK_SUCCESS.equals(result)) {
        return true;
    }
    return false;

}
 
Example #20
Source File: EnhancedJedisCluster.java    From super-cloudops with Apache License 2.0 5 votes vote down vote up
@Override
public byte[] getSet(final byte[] key, final byte[] value) {
	checkArgumentsSpecification(key);
	return new EnhancedJedisClusterCommand<byte[]>(connectionHandler, maxAttempts) {
		@Override
		public byte[] doExecute(Jedis connection) {
			return connection.getSet(key, value);
		}
	}.runBinary(key);
}
 
Example #21
Source File: JedisClientPool.java    From BigDataPlatform with GNU General Public License v3.0 5 votes vote down vote up
@Override
public String hget(String key, String field) {
	Jedis jedis = jedisPool.getResource();
	String result = jedis.hget(key, field);
	jedis.close();
	return result;
}
 
Example #22
Source File: JedisUtil.java    From BigData with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 根据key获取记录
 * 
 * @param String
 *            key
 * @return 值
 * */
public String get(String key) {
	// ShardedJedis sjedis = getShardedJedis();
	Jedis sjedis = getJedis();
	String value = sjedis.get(key);
	returnJedis(sjedis);
	return value;
}
 
Example #23
Source File: EnhancedJedisCluster.java    From super-cloudops with Apache License 2.0 5 votes vote down vote up
@Override
public Long bitcount(final String key) {
	checkArgumentsSpecification(key);
	return new EnhancedJedisClusterCommand<Long>(connectionHandler, maxAttempts) {
		@Override
		public Long doExecute(Jedis connection) {
			return connection.bitcount(key);
		}
	}.run(key);
}
 
Example #24
Source File: RedisCache.java    From jetcache with Apache License 2.0 5 votes vote down vote up
@Override
protected MultiGetResult<K, V> do_GET_ALL(Set<? extends K> keys) {
    try (Jedis jedis = getReadPool().getResource()) {
        ArrayList<K> keyList = new ArrayList<K>(keys);
        byte[][] newKeys = keyList.stream().map((k) -> buildKey(k)).toArray(byte[][]::new);

        Map<K, CacheGetResult<V>> resultMap = new HashMap<>();
        if (newKeys.length > 0) {
            List mgetResults = jedis.mget(newKeys);
            for (int i = 0; i < mgetResults.size(); i++) {
                Object value = mgetResults.get(i);
                K key = keyList.get(i);
                if (value != null) {
                    CacheValueHolder<V> holder = (CacheValueHolder<V>) valueDecoder.apply((byte[]) value);
                    if (System.currentTimeMillis() >= holder.getExpireTime()) {
                        resultMap.put(key, CacheGetResult.EXPIRED_WITHOUT_MSG);
                    } else {
                        CacheGetResult<V> r = new CacheGetResult<V>(CacheResultCode.SUCCESS, null, holder);
                        resultMap.put(key, r);
                    }
                } else {
                    resultMap.put(key, CacheGetResult.NOT_EXISTS_WITHOUT_MSG);
                }
            }
        }
        return new MultiGetResult<K, V>(CacheResultCode.SUCCESS, null, resultMap);
    } catch (Exception ex) {
        logError("GET_ALL", "keys(" + keys.size() + ")", ex);
        return new MultiGetResult<K, V>(ex);
    }
}
 
Example #25
Source File: EnhancedJedisCluster.java    From super-cloudops with Apache License 2.0 5 votes vote down vote up
@Override
public Long sunionstore(final byte[] dstkey, final byte[]... keys) {
	checkArgumentsSpecification(dstkey);
	checkArgumentsSpecification(keys);
	byte[][] wholeKeys = KeyMergeUtil.merge(dstkey, keys);

	return new EnhancedJedisClusterCommand<Long>(connectionHandler, maxAttempts) {
		@Override
		public Long doExecute(Jedis connection) {
			return connection.sunionstore(dstkey, keys);
		}
	}.runBinary(wholeKeys.length, wholeKeys);
}
 
Example #26
Source File: JedisUtils.java    From fw-spring-cloud with Apache License 2.0 5 votes vote down vote up
/**
 * <p>
 * 通过key 删除指定的 field
 * </p>
 *
 * @param key
 * @param fields
 *            可以是 一个 field 也可以是 一个数组
 * @return
 */
public Long hdel(String key, String... fields) {
    Jedis jedis = null;
    Long res = null;
    try {
        jedis = jedisPool.getResource();
        res = jedis.hdel(key, fields);
    } catch (Exception e) {

        log.error(e.getMessage());
    } finally {
        returnResource(jedisPool, jedis);
    }
    return res;
}
 
Example #27
Source File: RedisJobStore.java    From redis-quartz with MIT License 5 votes vote down vote up
/**
 * Resume a job in redis.
 *
 * @param jobKey the job key
 * @param jedis thread-safe redis connection
 * @throws JobPersistenceException
 */
private void resumeJob(JobKey jobKey, Jedis jedis) throws JobPersistenceException {
	String jobHashKey = createJobHashKey(jobKey.getGroup(),jobKey.getName());
	if (!jedis.sismember(JOBS_SET, jobHashKey))
		throw new JobPersistenceException("job: " + jobHashKey + " des not exist");
		
	List<OperableTrigger> triggers = getTriggersForJob(jobKey);
	for (OperableTrigger trigger : triggers)
		resumeTrigger(trigger, jedis);
}
 
Example #28
Source File: JedisUtil.java    From ProjectStudy with MIT License 5 votes vote down vote up
/**
 * 模糊查询获取key集合(keys的速度非常快,但在一个大的数据库中使用它仍然可能造成性能问题,生产不推荐使用)
 *
 * @param key
 * @return java.util.Set<java.lang.String>
 * @author Wang926454
 * @date 2018/9/6 9:43
 */
public static Set<String> keysS(String key) {
    try (Jedis jedis = jedisPool.getResource()) {
        return jedis.keys(key);
    } catch (Exception e) {
        logger.error("模糊查询Redis的键集合keysS方法异常:key=" + key + " cause=" + e.getMessage());
    }
    return null;
}
 
Example #29
Source File: EnhancedJedisCluster.java    From super-cloudops with Apache License 2.0 5 votes vote down vote up
@Override
public String hmset(final String key, final Map<String, String> hash) {
	checkArgumentsSpecification(key);
	return new EnhancedJedisClusterCommand<String>(connectionHandler, maxAttempts) {
		@Override
		public String doExecute(Jedis connection) {
			return connection.hmset(key, hash);
		}
	}.run(key);
}
 
Example #30
Source File: JedisUtils.java    From fw-spring-cloud with Apache License 2.0 5 votes vote down vote up
/**
 * <p>
 * 通过key返回所有的field
 * </p>
 *
 * @param key
 * @return
 */
public Set<String> hkeys(String key) {
    Jedis jedis = null;
    Set<String> res = null;
    try {
        jedis = jedisPool.getResource();
        res = jedis.hkeys(key);
    } catch (Exception e) {

        log.error(e.getMessage());
    } finally {
        returnResource(jedisPool, jedis);
    }
    return res;
}