最全Redis工具类

类结构图:
在这里插入图片描述

BaseJedisHandler

package com.wj.redis;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * 抽象 Jedis 共有方法
 */
public abstract class BaseJedisHandler implements Constants {

    /**
     * jedis 连接池
     */
    private static JedisPool jedisPool;

    BaseJedisHandler() {
    }

    static {

        JedisPoolConfig config = new JedisPoolConfig();

        /*
         * 控制一个 pool 可分配多少个 jedis 实例,通过 pool.getResource() 来获取
         *
         * 如果赋值为-1,则表示不限制
         *
         * 如果 pool 已经分配了 maxActive 个 jedis 实例,则此时pool的状态为exhausted(耗尽)
         */
        config.setMaxTotal(500);

        /*
         * 控制一个 pool 最多有多少个状态为 idle(空闲的) 的 jedis 实例。
         */
        config.setMaxIdle(5);

        /*
         * 表示当 borrow(引入) 一个 jedis 实例时,最大的等待时间,如果超过等待时间,则直接抛出 JedisConnectionException
         */
        config.setMaxWaitMillis(100_1000);

        /*
         * 在 borrow 一个 jedis 实例时,是否提前进行 validate 操作
         *
         * 如果为true,则得到的 jedis 实例均是可用的
         */
        config.setTestOnBorrow(true);


        /* redis如果设置了密码 */
        // jedisPool = new JedisPool(config, "localhost", 6379, 10000, "password");

        /* redis未设置了密码 */
        jedisPool = new JedisPool(config, "localhost", 6379);
    }

    /**
     * 从jedis连接池中获取获取jedis对象
     *
     * @return Jedis 对象
     */
    Jedis getJedis() {
        return jedisPool.getResource();
    }

    /**
     * 回收 jedis( 放到finally中 )
     *
     * @param jedis 待回收的Jedis
     */
    void returnJedis(Jedis jedis) {
        if (null != jedis) {
            jedis.close();
        }
    }

    /**
     * 获取 StringsHandler
     *
     * @return StringsHandler
     */
    public static StringsHandler newStringsInstance() {
        return StringsHandler.getInstance();
    }

    /**
     * 获取 JedisHandler
     *
     * @return JedisHandler
     */
    public static HashHandler newHashHandler() {
        return HashHandler.getInstance();
    }

    /**
     * 获取 KeyHandler
     *
     * @return KeyHandler
     */
    public static KeyHandler newKeyHandler() {
        return KeyHandler.getInstance();
    }

    /**
     * 获取 ListsHandler
     *
     * @return ListsHandler
     */
    public static ListsHandler newListsHandler() {
        return ListsHandler.getInstance();
    }

    /**
     * 获取 ListsHandler
     *
     * @return ListsHandler
     */
    public static SetsHandler newSetsHandler() {
        return SetsHandler.getInstance();
    }

}

KeyHandler

package com.wj.redis;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.SortingParams;
import redis.clients.util.SafeEncoder;

import java.util.List;
import java.util.Set;

/**
 * Key Handler
 */
class KeyHandler extends BaseJedisHandler {

    private static final KeyHandler INSTANCE = new KeyHandler();

    public static KeyHandler getInstance() {
        return INSTANCE;
    }

    /**
     * Delete all the keys of all the existing databases
     */
    public String flushAll() {
        Jedis jedis = getJedis();

        try {
            return jedis.flushAll();
        } finally {
            returnJedis(jedis);
        }
    }

    /**
     * Atomically renames the key oldKey to newKey.<p>
     * <p>
     * If the source and destination name are the same an error is returned.
     * <p>
     * If newkey already exists it is overwritten.
     *
     * @param oldKey old key
     * @param newKey new key
     * @return status
     */
    public String rename(String oldKey, String newKey) {
        return rename(SafeEncoder.encode(oldKey), SafeEncoder.encode(newKey));
    }

    /**
     * Rename oldKey into newKey but fails if the destination key newKey already exists.
     *
     * @param oldKey old key
     * @param newKey new key
     * @return status
     */
    public long renamenx(String oldKey, String newKey) {
        Jedis jedis = getJedis();

        try {
            return jedis.renamenx(oldKey, newKey);
        } finally {
            returnJedis(jedis);
        }
    }

    /**
     * Atomically renames the key oldKey to newKey
     *
     * @param oldKey old key
     * @param newKey new key
     * @return status
     */
    public String rename(byte[] oldKey, byte[] newKey) {
        Jedis jedis = getJedis();
        String status = jedis.rename(oldKey, newKey);
        returnJedis(jedis);
        return status;
    }

    /**
     * Set a default timeout on the specified key
     *
     * @param key Key
     * @return result
     */
    public long expire(String key) {
        return expire(key, EXPIRE);
    }

    /**
     * Set a timeout on the specified key
     *
     * @param key     Key
     * @param seconds second, -1 : no expired
     * @return result
     */
    public long expire(String key, int seconds) {
        Jedis jedis = getJedis();
        try {
            return jedis.expire(key, seconds);
        } finally {
            returnJedis(jedis);
        }
    }

    /**
     * expire at timestamp (UTC)
     *
     * @param key       Key
     * @param timestamp long
     * @return result
     */
    public long expireAt(String key, long timestamp) {
        Jedis jedis = getJedis();

        try {
            return jedis.expireAt(key, timestamp);
        } finally {
            returnJedis(jedis);
        }
    }

    /**
     * returns the remaining time to live in seconds
     *
     * @param key Key
     * @return time to live in seconds
     */
    public long ttl(String key) {
        Jedis jedis = getJedis();

        try {
            return jedis.ttl(key);
        } finally {
            returnJedis(jedis);
        }
    }

    /**
     * Undo a expire at turning the expire key into a normal key.(no expire)
     *
     * @param key Key
     * @return result
     */
    public long persist(String key) {
        Jedis jedis = getJedis();

        try {
            return jedis.persist(key);
        } finally {
            returnJedis(jedis);
        }
    }

    /**
     * Remove the specified keys.
     *
     * @param keys keys to removed
     * @return returns the number of keys removed
     */
    public long del(String... keys) {
        Jedis jedis = getJedis();

        try {
            return jedis.del(keys);
        } finally {
            returnJedis(jedis);
        }
    }

    /**
     * Remove the specified keys.
     *
     * @param keys keys to removed
     * @return returns the number of keys removed
     */
    public long del(byte[]... keys) {
        Jedis jedis = getJedis();

        try {
            return jedis.del(keys);
        } finally {
            returnJedis(jedis);
        }
    }

    /**
     * Test if the specified key exists.
     *
     * @param key Key
     * @return The command returns true if the key exists, otherwise false is returned.
     */
    public boolean exists(String key) {
        Jedis jedis = getJedis();

        try {
            return jedis.exists(key);
        } finally {
            returnJedis(jedis);
        }
    }

    /**
     * Sort the elements contained in the List, Set, or Sorted Set value at key.
     *
     * @param key Key
     * @return the list of numbers ordered from the smallest to the biggest number.
     */
    public List<String> sort(String key) {
        Jedis sjedis = getJedis();

        try {
            return sjedis.sort(key);
        } finally {
            returnJedis(sjedis);
        }
    }

    /**
     * Sort a Set or a List accordingly to the specified parameters.
     *
     * @param key               Key
     * @param sortingParameters 定义排序类型或limit的起止位置.
     * @return List<String> a list of sorted elements.
     **/
    public List<String> sort(String key, SortingParams sortingParameters) {
        Jedis jedis = getJedis();

        try {
            return jedis.sort(key, sortingParameters);
        } finally {
            returnJedis(jedis);
        }
    }

    /**
     * Return the type of the value stored at key in form of a string.
     * <p>
     * The type can be one of "none", "string", "list", "set".
     * <p>
     * "none" is returned if the key does not exist.
     *
     * @param key Key
     * @return String string|list|set|set|hash
     **/
    public String type(String key) {
        Jedis jedis = getJedis();

        try {
            return jedis.type(key);
        } finally {
            returnJedis(jedis);
        }
    }

    /**
     * Returns all the keys matching the glob-style pattern
     *
     * @param pattern pattern
     * @return Multi bulk reply
     */
    public Set<String> keys(String pattern) {
        Jedis jedis = getJedis();

        try {
            return jedis.keys(pattern);
        } finally {
            returnJedis(jedis);
        }
    }

}

StringsHandler

package com.wj.redis;

import redis.clients.jedis.Jedis;
import redis.clients.util.SafeEncoder;

import java.util.List;

/**
 * Strings Handler
 */
public class StringsHandler extends BaseJedisHandler {

    private static final StringsHandler INSTANCE = new StringsHandler();

    public static StringsHandler getInstance() {
        return INSTANCE;
    }

    /**
     * Get the value of the specified key.
     *
     * @param key Key
     * @return Value
     */
    public String get(String key) {
        Jedis jedis = getJedis();

        try {
            return jedis.get(key);
        } finally {
            returnJedis(jedis);
        }
    }

    /**
     * Get the value of the specified key.
     *
     * @param key Key
     * @return Value
     */
    public byte[] get(byte[] key) {
        Jedis jedis = getJedis();

        try {
            return jedis.get(key);
        } finally {
            returnJedis(jedis);
        }
    }

    /**
     * The command is exactly equivalent to the following group of commands: SET + EXPIRE. The operation is atomic.
     *
     * @param key     Key
     * @param seconds 过期时间,以秒为单位
     * @param value   Value
     * @return Status code
     */
    public String setEx(String key, int seconds, String value) {
        Jedis jedis = getJedis();

        try {
            return jedis.setex(key, seconds, value);
        } finally {
            returnJedis(jedis);
        }
    }

    /**
     * The command is exactly equivalent to the following group of commands: SET + EXPIRE. The operation is atomic.
     *
     * @param key     Key
     * @param seconds 过期时间,以秒为单位
     * @param value   Value
     * @return Status code
     */
    public String setEx(byte[] key, int seconds, byte[] value) {
        Jedis jedis = getJedis();

        try {
            return jedis.setex(key, seconds, value);
        } finally {
            returnJedis(jedis);
        }
    }

    /**
     * if the key already exists no operation is performed
     *
     * @param key   Key
     * @param value Value
     * @return 1 if the key was set 0 if the key was not set
     */
    public long setnx(String key, String value) {
        Jedis jedis = getJedis();

        try {
            return jedis.setnx(key, value);
        } finally {
            returnJedis(jedis);
        }
    }

    /**
     * Set the string value as value of the key. The string can't be longer than 1073741824 bytes (1 GB).
     *
     * @param key   Key
     * @param value Value
     * @return Status code
     */
    public String set(String key, String value) {
        return set(SafeEncoder.encode(key), SafeEncoder.encode(value));
    }

    /**
     * Set the string value as value of the key. The string can't be longer than 1073741824 bytes (1 GB).
     *
     * @param key   Key
     * @param value Value
     * @return Status code
     */
    public String set(String key, byte[] value) {
        return set(SafeEncoder.encode(key), value);
    }

    /**
     * Set the string value as value of the key. The string can't be longer than 1073741824 bytes (1 GB).
     *
     * @param key   Key
     * @param value Value
     * @return Status code
     */
    public String set(byte[] key, byte[] value) {
        Jedis jedis = getJedis();

        try {
            return jedis.set(key, value);
        } finally {
            returnJedis(jedis);
        }
    }

    /**
     * 从指定位置开始插入数据,插入的数据会覆盖指定位置以后的数据<br/>
     * <p>
     * 例:String str1="123456789";<br/>
     * <p>
     * 对str1操作后setRange(key,4,0000),str1="123400009";
     *
     * @param key    Key
     * @param offset offset
     * @param value  value
     * @return long value的长度
     */
    public long setRange(String key, long offset, String value) {
        Jedis jedis = getJedis();

        try {
            return jedis.setrange(key, offset, value);
        } finally {
            returnJedis(jedis);
        }
    }

    /**
     * If the key already exists and is a string, this command appends the provided value at the end of the string.
     * <p>
     * If the key does not exist it is created and set as an empty string
     *
     * @param key   Key
     * @param value Value
     * @return specifically the total length of the string after the append operation.
     **/
    public long append(String key, String value) {
        Jedis jedis = getJedis();

        try {
            return jedis.append(key, value);
        } finally {
            returnJedis(jedis);
        }
    }

    /**
     * 将key对应的value减去指定的值,只有value可以转为数字时该方法才可用
     *
     * @param key    Key
     * @param number 要减去的值
     * @return the new value of key after the increment.
     */
    public long decrBy(String key, long number) {
        Jedis jedis = getJedis();

        try {
            return jedis.decrBy(key, number);
        } finally {
            returnJedis(jedis);
        }
    }

    /**
     * 将key对应的value加上指定的值,只有value可以转为数字时该方法才可用
     * <p>
     * ( 可以作为获取唯一id的方法 )
     *
     * @param key    Key
     * @param number 要减去的值
     * @return the new value of key after the increment.
     */
    public long incrBy(String key, long number) {
        Jedis jedis = getJedis();

        try {
            return jedis.incrBy(key, number);
        } finally {
            returnJedis(jedis);
        }
    }

    /**
     * 对指定key对应的value进行截取
     *
     * @param key         Key
     * @param startOffset 开始位置(包含)
     * @param endOffset   结束位置(包含)
     * @return String 截取的值
     */
    public String getrange(String key, long startOffset, long endOffset) {
        Jedis jedis = getJedis();

        try {
            return jedis.getrange(key, startOffset, endOffset);
        } finally {
            returnJedis(jedis);
        }
    }

    /**
     * GETSET is an atomic set this value and return the old value command.
     * <p>
     * Set key to the string value and return the old value stored at key.
     *
     * @param key   Key
     * @param value Value
     * @return return the old value
     */
    public String getSet(String key, String value) {
        Jedis jedis = getJedis();

        try {
            return jedis.getSet(key, value);
        } finally {
            returnJedis(jedis);
        }
    }

    /**
     * Get the values of all the specified keys.
     *
     * @param keys Keys
     * @return 值的集合
     */
    public List<String> mget(String... keys) {
        Jedis jedis = getJedis();

        try {
            return jedis.mget(keys);
        } finally {
            returnJedis(jedis);
        }
    }

    /**
     * Set the the respective keys to the respective values.
     *
     * @param keysvalues 例:keysvalues="key1","value1","key2","value2";
     * @return Status code reply Basically +OK as MSET can't fail
     */
    public String mset(String... keysvalues) {
        Jedis jedis = getJedis();

        try {
            return jedis.mset(keysvalues);
        } finally {
            returnJedis(jedis);
        }
    }

    /**
     * 获取key对应的值的长度
     *
     * @param key Key
     * @return value值得长度
     */
    public long strlen(String key) {
        Jedis jedis = getJedis();

        try {
            return jedis.strlen(key);
        } finally {
            returnJedis(jedis);
        }
    }

}

HashHandler

package com.wj.redis;

import redis.clients.jedis.Jedis;

import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Hash Handler
 */
public class HashHandler extends BaseJedisHandler {

    private static final HashHandler INSTANCE = new HashHandler();

    public static HashHandler getInstance() {
        return INSTANCE;
    }


    /**
     * Remove the specified field from an hash stored at key.
     *
     * @param key   Key
     * @param field 存储的名字
     * @return 状态码,1成功,0失败
     */
    public long hdel(String key, String field) {
        Jedis jedis = getJedis();

        try {
            return jedis.hdel(key, field);
        } finally {
            returnJedis(jedis);
        }
    }

    /**
     * Test for existence of a specified field in a hash.
     *
     * @param key   Key
     * @param field 存储的名字
     * @return Return true if the hash stored at key contains the specified field. Return false if the key is not found or the field is not present.
     */
    public boolean hexists(String key, String field) {
        Jedis jedis = getJedis();

        try {
            return jedis.hexists(key, field);
        } finally {
            returnJedis(jedis);
        }
    }

    /**
     * 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.
     *
     * @param key   Key
     * @param field Field
     * @return the value associated to the specified field.
     */
    public String hget(String key, String field) {
        Jedis jedis = getJedis();

        try {
            return jedis.hget(key, field);
        } finally {
            returnJedis(jedis);
        }
    }

    /**
     * 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.
     *
     * @param key   Key
     * @param field Field
     * @return the value associated to the specified field.
     */
    public byte[] hget(byte[] key, byte[] field) {
        Jedis jedis = getJedis();

        try {
            return jedis.hget(key, field);
        } finally {
            returnJedis(jedis);
        }
    }

    /**
     * Return all the fields and associated values in a hash.
     *
     * @param key Key
     * @return Map<String, String>
     */
    public Map<String, String> hgetAll(String key) {
        Jedis jedis = getJedis();

        try {
            return jedis.hgetAll(key);
        } finally {
            returnJedis(jedis);
        }
    }

    /**
     * Set the specified hash field to the specified value.
     * <p>
     * If key does not exist, a new key holding a hash is created.
     *
     * @param key   Key
     * @param field Field
     * @param value Value
     * @return If the field already exists, and the HSET just produced an update of the value, 0 is returned, otherwise if a new field is created 1 is returned.
     **/
    public long hset(String key, String field, String value) {
        Jedis jedis = getJedis();

        try {
            return jedis.hset(key, field, value);
        } finally {
            returnJedis(jedis);
        }
    }

    /**
     * Set the specified hash field to the specified value.
     * <p>
     * If key does not exist, a new key holding a hash is created.
     *
     * @param key   Key
     * @param field Field
     * @param value Value
     * @return If the field already exists, and the HSET just produced an update of the value, 0 is returned, otherwise if a new field is created 1 is returned.
     */
    public long hset(String key, String field, byte[] value) {
        Jedis jedis = getJedis();

        try {
            return jedis.hset(key.getBytes(), field.getBytes(), value);
        } finally {
            returnJedis(jedis);
        }
    }

    /**
     * Set the specified hash field to the specified value if the field not exists.
     *
     * @param key   Key
     * @param field Field
     * @param value Value
     * @return If the field already exists, 0 is returned, otherwise if a new field is created 1 is returned.
     **/
    public long hsetnx(String key, String field, String value) {
        Jedis jedis = getJedis();

        try {
            return jedis.hsetnx(key, field, value);
        } finally {
            returnJedis(jedis);
        }
    }

    /**
     * Return all the values in a hash.
     *
     * @param key Key
     * @return All the fields values contained into a hash.
     */
    public List<String> hvals(String key) {
        Jedis jedis = getJedis();

        try {
            return jedis.hvals(key);
        } finally {
            returnJedis(jedis);
        }
    }

    /**
     * Increment the number stored at field in the hash at key by value.
     *
     * @param key   Key
     * @param field Field
     * @param value 要增加的值,可以是负数
     * @return The new value at field after the increment operation.
     */
    public long hincrby(String key, String field, long value) {
        Jedis jedis = getJedis();

        try {
            return jedis.hincrBy(key, field, value);
        } finally {
            returnJedis(jedis);
        }
    }

    /**
     * Return all the fields in a hash.
     *
     * @param key Key
     * @return All the fields names contained into a hash.
     */
    public Set<String> hkeys(String key) {
        Jedis jedis = getJedis();

        try {
            return jedis.hkeys(key);
        } finally {
            returnJedis(jedis);
        }
    }

    /**
     * Return the number of items in a hash.
     *
     * @param key Key
     * @return The number of entries (fields) contained in the hash stored at key. If the specified key does not exist, 0 is returned assuming an empty hash.
     */
    public long hlen(String key) {
        Jedis jedis = getJedis();

        try {
            return jedis.hlen(key);
        } finally {
            returnJedis(jedis);
        }
    }

    /**
     * Retrieve the values associated to the specified fields.
     *
     * @param key    Key
     * @param fields 存储位置
     * @return Multi Bulk Reply specifically a list of all the values associated with the specified fields, in the same order of the request.
     */
    public List<String> hmget(String key, String... fields) {
        Jedis jedis = getJedis();

        try {
            return jedis.hmget(key, fields);
        } finally {
            returnJedis(jedis);
        }
    }

    /**
     * Retrieve the values associated to the specified fields.
     *
     * @param key    Key
     * @param fields 存储位置
     * @return Multi Bulk Reply specifically a list of all the values associated with the specified fields, in the same order of the request.
     */
    public List<byte[]> hmget(byte[] key, byte[]... fields) {
        Jedis jedis = getJedis();

        try {
            return jedis.hmget(key, fields);
        } finally {
            returnJedis(jedis);
        }
    }

    /**
     * Set the respective fields to the respective values. HMSET replaces old values with new values.
     * <p>
     * If key does not exist, a new key holding a hash is created.
     *
     * @param key Key
     * @param map 对应关系
     * @return Return OK or Exception if hash is empty
     */
    public String hmset(String key, Map<String, String> map) {
        Jedis jedis = getJedis();

        try {
            return jedis.hmset(key, map);
        } finally {
            returnJedis(jedis);
        }
    }

    /**
     * Set the respective fields to the respective values. HMSET replaces old values with new values.
     * <p>
     * If key does not exist, a new key holding a hash is created.
     *
     * @param key Key
     * @param map 对应关系
     * @return Return OK or Exception if hash is empty
     */
    public String hmset(byte[] key, Map<byte[], byte[]> map) {
        Jedis jedis = getJedis();

        try {
            return jedis.hmset(key, map);
        } finally {
            returnJedis(jedis);
        }
    }

}

ListsHandler

package com.wj.redis;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.ListPosition;
import redis.clients.util.SafeEncoder;

import java.util.List;

/**
 * Lists Handler
 */
public class ListsHandler extends BaseJedisHandler {

    private static final ListsHandler INSTANCE = new ListsHandler();

    public static ListsHandler getInstance() {
        return INSTANCE;
    }

    /**
     * Return the length of the list stored at the specified key.
     *
     * @param key Key
     * @return The length of the list.
     */
    public long llen(byte[] key) {
        Jedis jedis = getJedis();

        try {
            return jedis.llen(key);
        } finally {
            returnJedis(jedis);
        }
    }

    /**
     * Return the length of the list stored at the specified key.
     *
     * @param key Key
     * @return The length of the list.
     */
    public long llen(String key) {
        return llen(SafeEncoder.encode(key));
    }


    /**
     * Set a new value as the element at index position of the List at key.
     *
     * @param key   Key
     * @param index 位置
     * @param value 值
     * @return Status code
     */
    public String lset(byte[] key, int index, byte[] value) {
        Jedis jedis = getJedis();

        try {
            return jedis.lset(key, index, value);
        } finally {
            returnJedis(jedis);
        }
    }

    /**
     * Set a new value as the element at index position of the List at key.
     *
     * @param key   Key
     * @param index 位置
     * @param value 值
     * @return Status code
     */
    public String lset(String key, int index, String value) {
        return lset(SafeEncoder.encode(key), index, SafeEncoder.encode(value));
    }

    /**
     * 在指定位置插入记录
     *
     * @param key   Key
     * @param where 前面插入或后面插入
     * @param pivot 相对位置的内容
     * @param value 插入的内容
     * @return 记录总数
     */
    public long linsert(byte[] key, ListPosition where, byte[] pivot, byte[] value) {
        Jedis jedis = getJedis();

        try {
            return jedis.linsert(key, where, pivot, value);
        } finally {
            returnJedis(jedis);
        }
    }

    /**
     * 在value的相对位置插入记录
     *
     * @param key   Key
     * @param where 前面插入或后面插入
     * @param pivot 相对位置的内容
     * @param value 插入的内容
     * @return 记录总数
     */
    public long linsert(String key, ListPosition where, String pivot, String value) {
        return linsert(SafeEncoder.encode(key), where, SafeEncoder.encode(pivot), SafeEncoder.encode(value));
    }

    /**
     * 获取List中指定位置的值
     *
     * @param key   Key
     * @param index 位置
     * @return 值
     **/
    public byte[] lindex(byte[] key, int index) {
        Jedis jedis = getJedis();

        try {
            return jedis.lindex(key, index);
        } finally {
            returnJedis(jedis);
        }
    }

    /**
     * 获取List中指定位置的值
     *
     * @param key   Key
     * @param index 位置
     * @return 值
     **/
    public String lindex(String key, int index) {
        return SafeEncoder.encode(lindex(SafeEncoder.encode(key), index));
    }

    /**
     * Atomically return and remove the first (LPOP) element of the list.
     *
     * @param key Key
     * @return 移出的记录
     */
    public byte[] lpop(byte[] key) {
        Jedis jedis = getJedis();

        try {
            return jedis.lpop(key);
        } finally {
            returnJedis(jedis);
        }
    }

    /**
     * Atomically return and remove the first (LPOP) element of the list.
     *
     * @param key Key
     * @return 移出的记录
     */
    public String lpop(String key) {
        return SafeEncoder.encode(lpop(SafeEncoder.encode(key)));
    }


    /**
     * Atomically return and remove the last (RPOP) element of the list.
     *
     * @param key Key
     * @return 移出的记录
     */
    public String rpop(String key) {
        Jedis jedis = getJedis();

        try {
            return jedis.rpop(key);
        } finally {
            returnJedis(jedis);
        }
    }

    /**
     * Add the string value to the head (LPUSH) of the list stored at key.
     *
     * @param key   Key
     * @param value Value
     * @return 记录总数
     */
    public long rpush(byte[] key, byte[] value) {
        Jedis jedis = getJedis();

        try {
            return jedis.rpush(key, value);
        } finally {
            returnJedis(jedis);
        }
    }

    /**
     * Add the string value to the head (LPUSH) of the list stored at key.
     *
     * @param key   Key
     * @param value Value
     * @return 记录总数
     */
    public long rpush(String key, String value) {
        Jedis jedis = getJedis();

        try {
            return jedis.rpush(key, value);
        } finally {
            returnJedis(jedis);
        }
    }

    /**
     * Add the string value to the tail (RPUSH) of the list stored at key.
     *
     * @param key   Key
     * @param value Value
     * @return 记录总数
     */
    public long lpush(byte[] key, byte[] value) {
        Jedis jedis = getJedis();

        try {
            return jedis.lpush(key, value);
        } finally {
            returnJedis(jedis);
        }
    }

    /**
     * Add the string value to the tail (RPUSH) of the list stored at key.
     *
     * @param key   Key
     * @param value Value
     * @return 记录总数
     */
    public long lpush(String key, String value) {
        return lpush(SafeEncoder.encode(key), SafeEncoder.encode(value));
    }


    /**
     * Return the specified elements of the list stored at the specified key.
     *
     * @param key   key
     * @param start start
     * @param end   end
     * @return List
     */
    public List<String> lrange(String key, long start, long end) {
        Jedis jedis = getJedis();

        try {
            return jedis.lrange(key, start, end);
        } finally {
            returnJedis(jedis);
        }
    }

    /**
     * Return the specified elements of the list stored at the specified key.
     *
     * @param key   key
     * @param start start
     * @param end   end
     * @return List
     */
    public List<byte[]> lrange(byte[] key, int start, int end) {
        Jedis jedis = getJedis();

        try {
            return jedis.lrange(key, start, end);
        } finally {
            returnJedis(jedis);
        }
    }

    /**
     * Remove the first count occurrences of the value element from the list.
     *
     * @param key   Key
     * @param count 要删除的数量,如果为负数则从List的尾部检查并删除符合的记录
     * @param value 要匹配的值
     * @return 删除后的List中的记录数
     */
    public long lrem(byte[] key, int count, byte[] value) {
        Jedis jedis = getJedis();

        try {
            return jedis.lrem(key, count, value);
        } finally {
            returnJedis(jedis);
        }
    }

    /**
     * Remove the first count occurrences of the value element from the list.
     *
     * @param key   Key
     * @param count 要删除的数量,如果为负数则从List的尾部检查并删除符合的记录
     * @param value 要匹配的值
     * @return 删除后的List中的记录数
     */
    public long lrem(String key, int count, String value) {
        return lrem(SafeEncoder.encode(key), count, SafeEncoder.encode(value));
    }

    /**
     * Trim an existing list so that it will contain only the specified range of elements specified.
     *
     * @param key   Key
     * @param start 记录的开始位置(0表示第一条记录)
     * @param end   记录的结束位置(如果为-1则表示最后一个,-2,-3以此类推)
     * @return Status code
     */
    public String ltrim(byte[] key, int start, int end) {
        Jedis jedis = getJedis();

        try {
            return jedis.ltrim(key, start, end);
        } finally {
            returnJedis(jedis);
        }
    }

    /**
     * Trim an existing list so that it will contain only the specified range of elements specified.
     *
     * @param key   Key
     * @param start 记录的开始位置(0表示第一条记录)
     * @param end   记录的结束位置(如果为-1则表示最后一个,-2,-3以此类推)
     * @return Status code
     */
    public String ltrim(String key, int start, int end) {
        return ltrim(SafeEncoder.encode(key), start, end);
    }

}

SetsHandler

package com.wj.redis;

import redis.clients.jedis.Jedis;

import java.util.Set;

/**
 * Set Handler
 */
public class SetsHandler extends BaseJedisHandler {

    private static final SetsHandler INSTANCE = new SetsHandler();

    public static SetsHandler getInstance() {
        return INSTANCE;
    }

    /**
     * Add the specified member to the set value stored at key
     *
     * @param key    Key
     * @param member Member
     * @return status, 0 or 1
     */
    public long sadd(String key, String... member) {
        Jedis jedis = getJedis();

        try {
            return jedis.sadd(key, member);
        } finally {
            returnJedis(jedis);
        }
    }

    /**
     * Add the specified member to the set value stored at key
     *
     * @param key    Key
     * @param member Member
     * @return status, 0 or 1
     */
    public long sadd(byte[] key, byte[] member) {
        Jedis jedis = getJedis();

        try {
            return jedis.sadd(key, member);
        } finally {
            returnJedis(jedis);
        }
    }

    /**
     * Return the set cardinality (number of elements)
     *
     * @param key Key
     * @return the cardinality (number of elements) of the set as an integer.
     */
    public long scard(String key) {
        Jedis jedis = getJedis();

        try {
            return jedis.scard(key);
        } finally {
            returnJedis(jedis);
        }
    }

    /**
     * Return the difference between the Set stored at key1 and all the Sets key2, ..., keyN
     *
     * @param keys keys
     * @return the members of a set resulting from the difference between the first set provided and all the successive sets.
     */
    public Set<String> sdiff(String... keys) {
        Jedis jedis = getJedis();

        try {
            return jedis.sdiff(keys);
        } finally {
            returnJedis(jedis);
        }
    }

    /**
     * This command works exactly like SDIFF but instead of being returned the resulting set is stored in dstKey.
     *
     * @param dstKey 新结果集的key
     * @param keys   比较的集合
     * @return 新集合中的记录数
     **/
    public long sdiffstore(String dstKey, String... keys) {
        Jedis jedis = getJedis();

        try {
            return jedis.sdiffstore(dstKey, keys);
        } finally {
            returnJedis(jedis);
        }
    }

    /**
     * Return the members of a set resulting from the intersection of all the sets hold at the specified keys.
     *
     * @param keys Keys
     * @return Multi bulk reply, specifically the list of common elements.
     **/
    public Set<String> sinter(String... keys) {
        Jedis jedis = getJedis();

        try {
            return jedis.sinter(keys);
        } finally {
            returnJedis(jedis);
        }
    }

    /**
     * This command works exactly like SINTER but instead of being returned the resulting set is stored as dstkey.
     *
     * @param dstkey 新结果集的key
     * @param keys   比较的集合
     * @return 新集合中的记录数
     **/
    public long sinterstore(String dstkey, String... keys) {
        Jedis jedis = getJedis();

        try {
            return jedis.sinterstore(dstkey, keys);
        } finally {
            returnJedis(jedis);
        }
    }

    /**
     * Return true if member is a member of the set stored at key, otherwise false is returned.
     *
     * @param key    Key
     * @param member member
     * @return Return true if member is a member of the set stored at key, otherwise false is returned.
     **/
    public boolean sismember(String key, String member) {
        Jedis jedis = getJedis();

        try {
            return jedis.sismember(key, member);
        } finally {
            returnJedis(jedis);
        }
    }

    /**
     * Return all the members (elements) of the set value stored at key. This is just syntax glue for SINTER.
     *
     * @param key Key
     * @return Multi bulk reply
     */
    public Set<String> smembers(String key) {
        Jedis jedis = getJedis();

        try {
            return jedis.smembers(key);
        } finally {
            returnJedis(jedis);
        }
    }

    /**
     * Return all the members (elements) of the set value stored at key. This is just syntax glue for SINTER.
     *
     * @param key Key
     * @return Multi bulk reply
     */
    public Set<byte[]> smembers(byte[] key) {
        Jedis jedis = getJedis();

        try {
            return jedis.smembers(key);
        } finally {
            returnJedis(jedis);
        }
    }

    /**
     * Move the specified member from the set at srcKey to the set at dstKey.
     *
     * @param srcKey srcKey
     * @param dstKey dstKey
     * @param member member
     * @return 1 if the element was moved 0 if the element was not found on the first set and no operation was performed
     */
    public long smove(String srcKey, String dstKey, String member) {
        Jedis jedis = getJedis();

        try {
            return jedis.smove(srcKey, dstKey, member);
        } finally {
            returnJedis(jedis);
        }
    }

    /**
     * Remove a random element from a Set returning it as return value.
     *
     * @param key Key
     * @return If the Set is empty or the key does not exist, a nil object is returned.
     */
    public String spop(String key) {
        Jedis jedis = getJedis();

        try {
            return jedis.spop(key);
        } finally {
            returnJedis(jedis);
        }
    }

    /**
     * Remove the specified member from the set value stored at key.
     * <p>
     * If member was not a member of the set no operation is performed.
     * <p>
     * If key does not hold a set value an error is returned.
     *
     * @param key    key
     * @param member member
     * @return 1 if the new element was removed 0 if the new element was not a member of the set
     */
    public long srem(String key, String member) {
        Jedis jedis = getJedis();

        try {
            return jedis.srem(key, member);
        } finally {
            returnJedis(jedis);
        }
    }

    /**
     * Return the members of a set resulting from the union of all the sets hold at the specified keys.
     *
     * @param keys keys
     * @return Multi bulk reply, specifically the list of common elements.
     */
    public Set<String> sunion(String... keys) {
        Jedis jedis = getJedis();

        try {
            return jedis.sunion(keys);
        } finally {
            returnJedis(jedis);
        }
    }

    /**
     * This command works exactly like SUNION but instead of being returned the resulting set is stored as dstKey.
     * <p>
     * Any existing value in dstKey will be over-written.
     *
     * @param dstKey dstKey
     * @param keys   keys
     * @return status code
     */
    public long sunionstore(String dstKey, String... keys) {
        Jedis jedis = getJedis();
        long s = jedis.sunionstore(dstKey, keys);
        returnJedis(jedis);
        return s;
    }
}

SortSetHandler

package com.wj.redis;

import redis.clients.jedis.Jedis;

import java.util.Map;
import java.util.Set;

/**
 * SortSet Handler
 */
public class SortSetHandler extends BaseJedisHandler {

    /**
     * Add the specified member having the specified score to the sorted set stored at key.
     *
     * @param key    Key
     * @param score  权重
     * @param member member
     * @return 1 if the new element was added 0 if the element was already a member of the sorted set and the score was updated
     */
    public long zadd(String key, double score, String member) {
        Jedis jedis = getJedis();

        try {
            return jedis.zadd(key, score, member);
        } finally {
            returnJedis(jedis);
        }
    }

    /**
     * Add the specified member having the specified score to the sorted set stored at key.
     *
     * @param key          Key
     * @param scoreMembers member-权重
     * @return 1 if the new element was added 0 if the element was already a member of the sorted set and the score was updated
     */
    public long zadd(String key, Map<String, Double> scoreMembers) {
        Jedis jedis = getJedis();

        try {
            return jedis.zadd(key, scoreMembers);
        } finally {
            returnJedis(jedis);
        }
    }

    /**
     * Return the sorted set cardinality (number of elements).
     *
     * @param key key
     * @return the cardinality (number of elements) of the set as an integer.
     */
    public long zcard(String key) {
        Jedis jedis = getJedis();

        try {
            return jedis.zcard(key);
        } finally {
            returnJedis(jedis);
        }
    }


    /**
     * 获取指定权重区间内集合的数量
     *
     * @param key key
     * @param min 最小排序位置
     * @param max 最大排序位置
     */
    public long zcount(String key, double min, double max) {
        Jedis jedis = getJedis();

        try {
            return jedis.zcount(key, min, max);
        } finally {
            returnJedis(jedis);
        }
    }


    /**
     * 返回指定位置的集合元素,0为第一个元素,-1为最后一个元素
     *
     * @param key   Key
     * @param start 开始位置(包含)
     * @param end   结束位置(包含)
     * @return Set<String>
     */
    public Set<String> zrange(String key, int start, int end) {
        Jedis jedis = getJedis();

        try {
            return jedis.zrange(key, start, end);
        } finally {
            returnJedis(jedis);
        }
    }

    /**
     * If member already exists in the sorted set adds the increment to its score and updates the position of the element in the sorted set accordingly.
     *
     * @param key    Key
     * @param score  要增的权重
     * @param member 要插入的值
     * @return The new score
     */
    public double zincrby(String key, double score, String member) {
        Jedis jedis = getJedis();

        try {
            return jedis.zincrby(key, score, member);
        } finally {
            returnJedis(jedis);
        }
    }


    /**
     * Return the all the elements in the sorted set at key with a score between min and max (including elements with score equal to min or max).
     *
     * @param key Key
     * @param min 上限权重
     * @param max 下限权重
     * @return Set<String>
     */
    public Set<String> zrangeByScore(String key, double min, double max) {
        Jedis jedis = getJedis();

        try {
            return jedis.zrangeByScore(key, min, max);
        } finally {
            returnJedis(jedis);
        }
    }

    /**
     * Return the rank (or index) of member in the sorted set at key, with scores being ordered from low to high.
     *
     * @param key    Key
     * @param member member
     * @return long 位置
     */
    public long zrank(String key, String member) {
        Jedis jedis = getJedis();

        try {
            return jedis.zrank(key, member);
        } finally {
            returnJedis(jedis);
        }
    }

    /**
     * Return the rank (or index) of member in the sorted set at key, with scores being ordered from high to low.
     *
     * @param key    key
     * @param member member
     * @return long 位置
     */
    public long zrevrank(String key, String member) {
        Jedis jedis = getJedis();

        try {
            return jedis.zrevrank(key, member);
        } finally {
            returnJedis(jedis);
        }
    }

    /**
     * Remove the specified member from the sorted set value stored at key.
     *
     * @param key    key
     * @param member member
     * @return 1 if the new element was removed 0 if the new element was not a member of the set
     */
    public long zrem(String key, String member) {
        Jedis jedis = getJedis();

        try {
            return jedis.zrem(key, member);
        } finally {
            returnJedis(jedis);
        }
    }

    /**
     * delete key
     *
     * @param key key
     * @return status
     */
    public long zrem(String key) {
        Jedis jedis = getJedis();

        try {
            return jedis.del(key);
        } finally {
            returnJedis(jedis);
        }
    }

    /**
     * Remove all elements in the sorted set at key with rank between start and end.
     *
     * @param key   Key
     * @param start 开始区间,从0开始(包含)
     * @param end   结束区间,-1为最后一个元素(包含)
     * @return specifically the number of elements removed.
     */
    public long zremrangeByRank(String key, int start, int end) {
        Jedis jedis = getJedis();

        try {
            return jedis.zremrangeByRank(key, start, end);
        } finally {
            returnJedis(jedis);
        }
    }

    /**
     * Remove all the elements in the sorted set at key with a score between min and max
     * <p>
     * (including elements with score equal to min or max).
     *
     * @param key Key
     * @param min 下限权重(包含)
     * @param max 上限权重(包含)
     * @return specifically the number of elements removed.
     */
    public long zremrangeByScore(String key, double min, double max) {
        Jedis jedis = getJedis();

        try {
            return jedis.zremrangeByScore(key, min, max);
        } finally {
            returnJedis(jedis);
        }
    }

    /**
     * 获取给定区间的元素,原始按照权重由高到低排序
     *
     * @param key   Key
     * @param start 开始区间,从0开始(包含)
     * @param end   结束区间,-1为最后一个元素(包含)
     * @return Set<String>
     */
    public Set<String> zrevrange(String key, int start, int end) {
        Jedis jedis = getJedis();

        try {
            return jedis.zrevrange(key, start, end);
        } finally {
            returnJedis(jedis);
        }
    }

    /**
     * Return the score of the specified element of the sorted set at key.
     * <p>
     * If the specified element does not exist in the sorted set, or the key does not exist at all, a special 'nil' value is returned.
     *
     * @param key    Key
     * @param member member
     * @return double 权重
     */
    public double zscore(String key, String member) {
        Jedis jedis = getJedis();

        try {
            return jedis.zscore(key, member);
        } finally {
            returnJedis(jedis);
        }
    }
}

用法实例

package com.wj.test;

import com.wj.redis.HashHandler;
import com.wj.redis.BaseJedisHandler;
import com.wj.redis.StringsHandler;
import org.junit.Test;

/**
 * Jedis Util demo
 */
public class JedisUtilTest {

    @Test
    public void test() {
        StringsHandler stringsHandler = BaseJedisHandler.newStringsInstance();
        stringsHandler.set("nnn", "nnnn");
        System.out.println("-----" + stringsHandler.get("nnn"));

        HashHandler hashHandler = BaseJedisHandler.newHashHandler();
        hashHandler.hset("hashKey", "field_hash", "field_value");
        System.out.println(hashHandler.hget("hashKey", "field_hash"));
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值