版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_36898043/article/details/82183190
一、由来
之前的redis pool的文章,讲解了如何封装一个redis pool以及操作redis中的字符串,博客地址如下:
https://blog.csdn.net/qq_36898043/article/details/82155202
还有一篇文章封装了一些 操作redis中的list 。。。。
https://blog.csdn.net/qq_36898043/article/details/82181654
还有一篇文章封装了一些 操作redis中的set 。。。。
https://blog.csdn.net/qq_36898043/article/details/82181793
还有一篇文章封装了一些 操作redis中的hash 。。。。
https://blog.csdn.net/qq_36898043/article/details/82181987
关于 hash相关操作命令可以参考runoob,连接地址如下:
http://www.runoob.com/redis/redis-commands.html
本文主要是封装一些 操作 redis中 key的相关方法。。。。。。
二、代码
package me.ele.redis;
import redis.clients.jedis.Jedis;
/**
* 操作redis中的key
*
* @author LZJ
* @create 2018-08-29 14:31
**/
public class KeyRedisOperator {
/**
* 设置key的过期时间
* 当key过期时,它会被自动删除
*
* @param pool
* @param key
* @param seconds
* @return
*/
public static long expired(MyRedisPool redisPool, String key, int seconds) {
Jedis jedis = redisPool.borrowJedis();
long count = jedis.expire(key, seconds);
redisPool.returnJedis(jedis);
return count;
}
/**
* 移除给定 key 的过期时间,使得 key 永不过期
*
* @param redisPool
* @param key
* @return 当过期时间移除成功时,返回 1, 如果 key 不存在或 key 没有设置过期时间,返回 0
*/
public static long persist(MyRedisPool redisPool, String key) {
Jedis jedis = redisPool.borrowJedis();
long count = jedis.persist(key);
redisPool.returnJedis(jedis);
return count;
}
/**
* 判断key是否存在
*
* @param redisPool
* @param key
* @return 若 key 存在,返回 1 ,否则返回 0
*/
public static boolean ifExist(MyRedisPool redisPool, String key) {
Jedis jedis = redisPool.borrowJedis();
boolean ifExist = jedis.exists(key);
redisPool.returnJedis(jedis);
return ifExist;
}
/**
* 判断key的存储类型
*
* @param redisPool
* @param key
* @return none (key不存在) string (字符串) list (列表) set (集合) zset (有序集) hash (哈希表)
*/
public static String type(MyRedisPool redisPool, String key) {
Jedis jedis = redisPool.borrowJedis();
String type = jedis.type(key);
redisPool.returnJedis(jedis);
return type;
}
/**
* 删除给定的一个或多个 key
* 不存在的 key 会被忽略
*
* @param redisPool
* @param key
* @return 被删除 key 的数量
*/
public static long delete(MyRedisPool redisPool, String... key) {
Jedis jedis = redisPool.borrowJedis();
long status = jedis.del(key);
redisPool.returnJedis(jedis);
return status;
}
/**
* 清空整个 Redis 服务器的数据(删除所有数据库的所有 key )
*
* @param redisPool
* @return 总是返回 OK
*/
public static String flushAll(MyRedisPool redisPool) {
Jedis jedis = redisPool.borrowJedis();
String flushAll = jedis.flushAll();
redisPool.returnJedis(jedis);
return flushAll;
}
}