redis的一些操作

时间:2024-11-09 11:37:18
public class WnsRedisFactory {

              private static Cache pool = null;
private static JedisConnectionFactory redisConnFactory = null; //对主缓存 test的操作
private static Cache getInstance() {
if (pool == null) {
pool = Redis.use("test");
}
return pool;
}
/**
* 通过key删除
*
* @param key
*/
public static void del(String key) throws Exception {
Cache redis = null; redis = getInstance();
redis.del(key); } public static void del(String key, String field) throws Exception {
Cache redis = null; redis = getInstance();
redis.hdel(key, field); }
/**
* 添加key value 并且设置存活时间
*
* @param key
* @param value
* @param liveTime
*/
public static void set(String key, String value, int liveTime) throws Exception {
Cache redis = null; redis = getInstance();
Jedis jedis =redis.getJedis();
jedis.set(key, value);
redis.expire(key, liveTime);
redis.close(jedis); } public static Long decrby(String key, int value) throws Exception {
Cache redis = null; redis = getInstance();
return redis.decrBy(key, value); } public static Long decr(String key) throws Exception {
Cache redis = null; redis = getInstance();
return redis.decr(key); }
/**
* 设置或者清除指定key的value上的某个位置的比特位,如果该key原先不存在,则新创建一个key,其value将会自动分配内存,
* 直到可以放下指定位置的bit值。
*
* @param key
* @param offset
* @param value true代表1,false代表0
* @return
* @return 返回原来位置的bit值是否是1,如果是1,则返回true,否则返回false。
*/
public static void setbit(String key,Long offset ,Boolean value,int liveTime)
{
Cache redis = null; redis = getInstance();
Jedis jedis = redis.getJedis();
try {
jedis.setbit(key, offset, value);
}
finally {redis.close(jedis);}
redis.expire(key, liveTime); } //计算传人二进制字符串 1的个数
public static long bitcount(String key)
{
Cache redis = null; redis = getInstance();
Jedis jedis = redis.getJedis();
try {
return jedis.bitcount(key);
}
finally {redis.close(jedis);} } //通过传人的op(and/or)将传人的二进制 与/非 传回结果
public static long bitop(BitOP op,String destKey,String ... srcKeys)
{
Cache redis = null;
redis = getInstance(); Jedis jedis = redis.getJedis();
long result = 0; result = jedis.bitop(op, destKey, srcKeys);
redis.close(jedis);
return result;
}
/**
* bitMap进行and运算
* RedisKeys.DAYBITOPDESTKEY 为静态变量
*/
// 换一种实现方式,不用 bitset 类,直接用redis的bit操作
public static int bitMapAnd( String...keys){
int result = 0;
BitOP op = BitOP.AND; try {
bitop(op, RedisKeys.DAYBITOPDESTKEY, keys);
result = (int) WnsRedisFactory.bitcount(RedisKeys.DAYBITOPDESTKEY); return result; } catch (Exception e) {
System.out.println("AND算法异常");
}
return 0;
} /**
* bitMap进行OR运算
*/
// 换一种实现方式,不用 bitset 类,直接用redis的bit操作
public static int bitMapOr( String...keys){
int result = 0;
BitOP op = BitOP.OR; try {
bitop(op, RedisKeys.DAYBITOPDESTKEY, keys);
result = (int) WnsRedisFactory.bitcount(RedisKeys.DAYBITOPDESTKEY); return result;
} catch (Exception e) {
System.out.println("OR算法异常");
}
return 0;
}
}