Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
   *
   * Copyright (c) 2013-2014 sagyf Yang. The Four Group.
   */
  package com.github.sog.plugin.redis;
  
 
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
 
 public class JedisKit {
     private static Logger LOG = Logger.getLogger(JedisKit.class);
     private static JedisPool pool;
 
     public static void init(JedisPool pool) {
         . = pool;
     }
 
     public static List<Objecttx(JedisAtom jedisAtom) {
         Jedis jedis = .getResource();
         Transaction trans = jedis.multi();
         jedisAtom.action(trans);
         return trans.exec();
 
     }
 
     public static <T> T call(JedisAction<T> jedisAction) {
         T result = null;
         Jedis jedis = .getResource();
         try {
             result = jedisAction.action(jedis);
         } catch (Exception e) {
             e.printStackTrace();
             .error(e.getMessage(), e);
         } finally {
             if (null != jedis)
                 .returnResource(jedis);
         }
         return result;
     }

    
query one Object from Redis with key

Parameters:
key using it get value from key-value database
Returns:
the Object which implements Serializable
 
 
     public static <T extends Serializable> T get(final String key) {
         return call(new JedisAction<T>() {
             @SuppressWarnings("unchecked")
             @Override
             public T action(Jedis jedis) {
                 Object result = null;
                 byte[] retVal = jedis.get(SafeEncoder.encode(key));
                 if (null != retVal) {
                     try {
                         result = SerializableKit.toObject(retVal);
                     } catch (Exception e) {
                         result = SafeEncoder.encode(retVal);
                     }
                 }
                 return (T) result;
             }
         });
     }

    
set object to key-value database with the specified key

Parameters:
key the unique key to indicate the value Object
value the value indicated by the key
Returns:
return true while the set operation is succeed,false by failed
 
 
     public static boolean set(final String keyfinal Serializable value) {
         return call(new JedisAction<Boolean>() {
             @Override
             public Boolean action(Jedis jedis) {
                 String retVal;
                 if (value instanceof String) {
                     retVal = jedis.set(key, (Stringvalue);
                 } else {
                     retVal = jedis.set(SafeEncoder.encode(key), SerializableKit.toByteArray(value));
                 }
                return "OK".equalsIgnoreCase(retVal);
            }
        });
    }

    
set object to key-value database with the specified key and EXPIRE time

Parameters:
key the unique key to indicate the value Object
value the value indicated by the key
seconds EXPIRE time
Returns:
return true while the set operation is succeed,false by failed
    public static boolean set(final String keyfinal Serializable valuefinal int seconds) {
        return call(new JedisAction<Boolean>() {
            @Override
            public Boolean action(Jedis jedis) {
                byte[] bytes;
                if (value instanceof String) {
                    bytes = SafeEncoder.encode((Stringvalue);
                } else {
                    bytes = SerializableKit.toByteArray(value);
                }
                String retVal = jedis.setex(SafeEncoder.encode(key), secondsbytes);
                return "OK".equalsIgnoreCase(retVal);
            }
        });
    }

    
query multiple Object from Redis with key

Parameters:
keys using it get value from key-value database
Returns:
the Object list which implements Serializable
    public static List<Serializablemquery(final String... keys) {
        return call(new JedisAction<List<Serializable>>() {
            @Override
            public List<Serializableaction(Jedis jedis) {
                List<Serializableresult = new ArrayList<Serializable>(keys.length);
                for (int index = 0; index < keys.lengthindex++)
                    result.add(null);
                byte[][] encodeKeys = new byte[keys.length][];
                for (int i = 0; i < keys.lengthi++)
                    encodeKeys[i] = SafeEncoder.encode(keys[i]);
                List<byte[]> retVals = jedis.mget(encodeKeys);
                if (null != retVals) {
                    int index = 0;
                    for (byte[] val : retVals) {
                        if (null != val)
                            result.set(index, SerializableKit.toObject(val));
                        index++;
                    }
                }
                return result;
            }
        });
    }
    public static List<StringmqueryStr(final String... keys) {
        return call(new JedisAction<List<String>>() {
            @Override
            public List<Stringaction(Jedis jedis) {
                return jedis.mget(keys);
            }
        });
    }
    public static boolean msaveOrUpdate(final Map<StringSerializablevalues) {
        return call(new JedisAction<Boolean>() {
            @Override
            public Boolean action(Jedis jedis) {
                byte[][] encodeValues = new byte[values.size() * 2][];
                int index = 0;
                Iterator<Entry<StringSerializable>> iter = values.entrySet().iterator();
                while (iter.hasNext()) {
                    Entry<StringSerializableentry = iter.next();
                    encodeValues[index++] = entry.getKey().getBytes();
                    encodeValues[index++] = SerializableKit.toByteArray(entry.getValue());
                }
                String retVal = jedis.mset(encodeValues);
                return "OK".equalsIgnoreCase(retVal);
            }
        });
    }
    public static boolean msaveOrUpdateStr(final Map<StringStringvalues) {
        return call(new JedisAction<Boolean>() {
            @Override
            public Boolean action(Jedis jedis) {
                Iterator<Entry<StringString>> iter = values.entrySet().iterator();
                int index = 0;
                String[] encodeValues = new String[values.size() * 2];
                while (iter.hasNext()) {
                    Entry<StringStringentry = iter.next();
                    encodeValues[index++] = entry.getKey();
                    encodeValues[index++] = entry.getValue();
                }
                return "OK".equalsIgnoreCase(jedis.mset(encodeValues));
            }
        });
    }

    
query keys set by pattern
    public static Set<Stringkeys(final String pattern) {
        return call(new JedisAction<Set<String>>() {
            @Override
            public Set<Stringaction(Jedis jedis) {
                return jedis.keys(pattern);
            }
        });
    }
    public static long del(final String... keys) {
        return call(new JedisAction<Long>() {
            @Override
            public Long action(Jedis jedis) {
                byte[][] encodeKeys = new byte[keys.length][];
                for (int i = 0; i < keys.lengthi++)
                    encodeKeys[i] = SafeEncoder.encode(keys[i]);
                return jedis.del(encodeKeys);
            }
        });
    }
    public static long listAdd(final String keyfinal Serializable value) {
        return call(new JedisAction<Long>() {
            @Override
            public Long action(Jedis jedis) {
                return jedis.rpush(SafeEncoder.encode(key), SerializableKit.toByteArray(value));
            }
        });
    }
    public static long listAddFirst(final String keyfinal Serializable value) {
        return call(new JedisAction<Long>() {
            @Override
            public Long action(Jedis jedis) {
                return jedis.lpush(SafeEncoder.encode(key), SerializableKit.toByteArray(value));
            }
        });
    }
    public static String type(final String key) {
        return call(new JedisAction<String>() {
            @Override
            public String action(Jedis jedis) {
                return jedis.type(SafeEncoder.encode(key));
            }
        });
    }
    @SuppressWarnings("unchecked")
    public static <T> List<T> queryList(final String keyfinal int startfinal int end) {
        return call(new JedisAction<List<T>>() {
            @Override
            public List<T> action(Jedis jedis) {
                List<T> result = Lists.newArrayList();
                List<byte[]> retVals = jedis.lrange(SafeEncoder.encode(key), startend);
                if (retVals != null) {
                    for (byte[] val : retVals) {
                        if (null != val)
                            result.add((T) SerializableKit.toObject(val));
                    }
                }
                return result;
            }
        });
    }
    public static long listSize(final String key) {
        return call(new JedisAction<Long>() {
            @Override
            public Long action(Jedis jedis) {
                return jedis.llen(SafeEncoder.encode(key));
            }
        });
    }
    public static boolean listTrim(final String keyfinal int startfinal int end) {
        return call(new JedisAction<Boolean>() {
            @Override
            public Boolean action(Jedis jedis) {
                return "OK".equalsIgnoreCase(jedis.ltrim(SafeEncoder.encode(key), startend));
            }
        });
    }
    public static long incrementAndGet(final String key) {
        return call(new JedisAction<Long>() {
            @Override
            public Long action(Jedis jedis) {
                return jedis.incr(key);
            }
        });
    }
    public static long decrementAndGet(final String key) {
        return call(new JedisAction<Long>() {
            @Override
            public Long action(Jedis jedis) {
                return jedis.decr(key);
            }
        });
    }
    public static long queryLong(final String key) {
        return call(new JedisAction<Long>() {
            @Override
            public Long action(Jedis jedis) {
                return Long.valueOf(jedis.get(key));
            }
        });
    }
    public static boolean hmset(final String keyfinal Map<StringStringvalues) {
        return call(new JedisAction<Boolean>() {
            @Override
            public Boolean action(Jedis jedis) {
                return "OK".equals(jedis.hmset(keyvalues));
            }
        });
    }
    public static List<Stringhvals(final String key) {
        return call(new JedisAction<List<String>>() {
            @Override
            public List<Stringaction(Jedis jedis) {
                return jedis.hvals(key);
            }
        });
    }
    public static List<Stringhmget(final String keyfinal String... fields) {
        return call(new JedisAction<List<String>>() {
            @Override
            public List<Stringaction(Jedis jedis) {
                return jedis.hmget(keyfields);
            }
        });
    }
    public static Double zincrby(final String keyfinal double scorefinal String member) {
        return call(new JedisAction<Double>() {
            @Override
            public Double action(Jedis jedis) {
                return jedis.zincrby(keyscoremember);
            }
        });
    }
    public static Double zscore(final String keyfinal String score) {
        return call(new JedisAction<Double>() {
            @Override
            public Double action(Jedis jedis) {
                return jedis.zscore(keyscore);
            }
        });
    }
    public static Long zadd(final String keyfinal double scorefinal String member) {
        return call(new JedisAction<Long>() {
            @Override
            public Long action(Jedis jedis) {
                return jedis.zadd(keyscoremember);
            }
        });
    }
    public static Set<TuplezrangeWithScores(final String keyfinal long startfinal long end) {
        return call(new JedisAction<Set<Tuple>>() {
            @Override
            public Set<Tupleaction(Jedis jedis) {
                return jedis.zrangeWithScores(keystartend);
            }
        });
    }
    public static String watch(final String... keys) {
        return call(new JedisAction<String>() {
            @Override
            public String action(Jedis jedis) {
                return jedis.watch(keys);
            }
        });
    }
    public static Long lpush(final String keyfinal Serializable value) {
        return call(new JedisAction<Long>() {
            @Override
            public Long action(Jedis jedis) {
                Long retVal;
                if (value instanceof String) {
                    retVal = jedis.lpush(key, (Stringvalue);
                } else {
                    retVal = jedis.lpush(SafeEncoder.encode(key), SerializableKit.toByteArray(value));
                }
                return retVal;
            }
        });
    }
    public static <T extends Serializable> T rpop(final String key) {
        return call(new JedisAction<T>() {
            @SuppressWarnings("unchecked")
            @Override
            public T action(Jedis jedis) {
                Object result = null;
                byte[] retVal = jedis.rpop(SafeEncoder.encode(key));
                if (null != retVal) {
                    try {
                        result = SerializableKit.toObject(retVal);
                    } catch (Exception e) {
                        result = SafeEncoder.encode(retVal);
                    }
                }
                return (T) result;
            }
        });
    }
    public static <T extends SerializableList<T> lrange(final String keyfinal long startfinal long end) {
        return call(new JedisAction<List<T>>() {
            @SuppressWarnings("unchecked")
            @Override
            public List<T> action(Jedis jedis) {
                List<T> list = Lists.newArrayList();
                List<byte[]> results = jedis.lrange(SafeEncoder.encode(key), startend);
                for (byte[] result : results) {
                    try {
                        list.add((T) SerializableKit.toObject(result));
                    } catch (Exception e) {
                        list.add((T) SafeEncoder.encode(result));
                    }
                }
                return list;
            }
        });
    }
    public static <T extends Serializable> T rpoplpush(final String srckeyfinal String dstkey) {
        return call(new JedisAction<T>() {
            @Override
            @SuppressWarnings("unchecked")
            public T action(Jedis jedis) {
                Object result = null;
                byte[] retVal = jedis.rpoplpush(SafeEncoder.encode(srckey), SafeEncoder.encode(dstkey));
                if (null != retVal) {
                    try {
                        result = SerializableKit.toObject(retVal);
                    } catch (Exception e) {
                        result = SafeEncoder.encode(retVal);
                    }
                }
                return (T) result;
            }
        });
    }
    public static Long lrem(String keySerializable value) {
        return lrem(key, 1, value);
    }
    public static Long lrem(final String keyfinal long countfinal Serializable value) {
        return call(new JedisAction<Long>() {
            @Override
            public Long action(Jedis jedis) {
                Long retVal;
                if (value instanceof String) {
                    retVal = jedis.lrem(keycount, (Stringvalue);
                } else {
                    retVal = jedis.lrem(SafeEncoder.encode(key), count, SerializableKit.toByteArray(value));
                }
                return retVal;
            }
        });
    }
New to GrepCode? Check out our FAQ X