redisTemplate封装参考:
https://blog.csdn.net/leinminna/article/details/115999431

1.jedis 基础属性

public class RedisUtils {
    private static JedisPool jedisPool;
    public static final String PREFIX = "0621B4751BC607DAB5EF2F391E4D2B69_";
    static Logger logger = Logger.getLogger(RedisUtils.class);

    private static final String REDIS_HOST_DEFAULT = "271.0.0.1";
    private static final int REDIS_PORT_DEFAULT = 6380;
    private static final int REDIS_MAXTOTAL_DEFAULT = 200;
    private static final int REDIS_MAXIDLE_DEFAULT = 25;
    private static final int REDIS_MAXWAIT_DEFAULT = 1000;
    private static final String REDIS_HOST = "redis.host";
    private static final String REDIS_PORT = "redis.port";
    private static final String REDIS_MAXTOTAL = "redis.maxTotal";
    private static final String REDIS_MAXIDLE = "redis.maxIdle";
    private static final String REDIS_MAXWAIT = "redis.maxWait";

    private static final String REDIS_PASSWORD = "redis.password";

    static {
        String host = SiteConfig.get(REDIS_HOST, REDIS_HOST_DEFAULT);
        int port = SiteConfig.getInt(REDIS_PORT, REDIS_PORT_DEFAULT);
        int maxTotal = SiteConfig.getInt(REDIS_MAXTOTAL, REDIS_MAXTOTAL_DEFAULT);
        int maxIdle = SiteConfig.getInt(REDIS_MAXIDLE, REDIS_MAXIDLE_DEFAULT);
        long maxWait = SiteConfig.getInt(REDIS_MAXWAIT, REDIS_MAXWAIT_DEFAULT);

        String password = SiteConfig.get(REDIS_PASSWORD);

        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(maxTotal);
        config.setMaxIdle(maxIdle);
        config.setMaxWaitMillis(maxWait);

        if (StringUtils.isEmpty(password)) {
            jedisPool = new JedisPool(config, host, port);
        } else {
            jedisPool = new JedisPool(config, host, port, 180000, password);

        }
    }
    ...
}

2. String 封装


    /**
     * string_key string_value
     *
     * @param key string_key
     * @return string_value
     */
    public static String get(String key) {
        Jedis jedis = jedisPool.getResource();
        try {
            return jedis.get(key);
        } catch (Exception e) {
            logger.error(e, e);
            jedisPool.returnBrokenResource(jedis);
            jedis = null;
            throw e;
        } finally {
            if (jedis != null) {
                jedisPool.returnResource(jedis);
            }
        }
    }

    /**
     * string_key string_value
     *
     * @param key     string_key
     * @param value   string_value
     * @param seconds 有效时间段
     */
    public static void set(String key, Serializable value, int seconds) {
        Jedis jedis = jedisPool.getResource();
        try {
            byte[] keyBytes = key.getBytes();
            jedis.set(keyBytes, SerializationUtil.serialize(value));
            jedis.expire(keyBytes, seconds);
        } catch (Exception e) {
            logger.error(e, e);
            jedisPool.returnBrokenResource(jedis);
            jedis = null;
            throw e;
        } finally {
            if (jedis != null) {
                jedisPool.returnResource(jedis);
            }
        }
    }

    /**
     * string_key string_value
     *
     * @param key   string_key
     * @param value string_value
     */
    public static void set(String key, Serializable value) {
        Jedis jedis = jedisPool.getResource();
        try {
            jedis.set(key.getBytes(), SerializationUtil.serialize(value));
        } catch (Exception e) {
            logger.error(e, e);
            jedisPool.returnBrokenResource(jedis);
            jedis = null;
            throw e;
        } finally {
            if (jedis != null) {
                jedisPool.returnResource(jedis);
            }
        }
    }

    /**
     * string_key string_value
     *
     * @param key   string_key
     * @param clazz T类
     * @param <T>   T 对象
     * @return T 对象
     */
    public static <T> T get(String key, Class<T> clazz) {

        Jedis jedis = jedisPool.getResource();
        try {
            byte[] data = jedis.get(key.getBytes());
            return data == null ? null : SerializationUtil.deserialize(data, clazz);
        } catch (Exception e) {
            logger.error(e, e);
            jedisPool.returnBrokenResource(jedis);
            jedis = null;
            throw e;
        } finally {
            if (jedis != null) {
                jedisPool.returnResource(jedis);
            }
        }
    }

    /**
     * string-key,string-value
     *
     * @param key     string-key
     * @param clazz   string-value 转 T 类
     * @param seconds 重新设置过期时间(秒)
     * @param <T>     T 的类型
     * @return 返回 T 对象
     */
    public static <T> T gas(String key, Class<T> clazz, int seconds) {
        Jedis jedis = jedisPool.getResource();
        try {
            byte[] keyBytes = key.getBytes();
            byte[] data = jedis.get(keyBytes);
            if (data != null) {
                jedis.expire(keyBytes, seconds);
                return SerializationUtil.deserialize(data, clazz);
            } else {
                return null;
            }
        } catch (Exception e) {
            logger.error(e, e);
            jedisPool.returnBrokenResource(jedis);
            jedis = null;
            throw e;
        } finally {
            if (jedis != null) {
                jedisPool.returnResource(jedis);
            }
        }
    }

    /**
     * string-key,string-value
     *
     * @param key     string-key
     * @param seconds 重新设置过期时间(秒)
     * @return 返回 jsonString
     */
    public static String gas(String key, int seconds) {
        Jedis jedis = jedisPool.getResource();
        try {
            String str = jedis.get(key);
            if (str != null) {
                jedis.expire(str, seconds);
            }
            return str;
        } catch (Exception e) {
            logger.error(e, e);
            jedisPool.returnBrokenResource(jedis);
            jedis = null;
            throw e;
        } finally {
            if (jedis != null) {
                jedisPool.returnResource(jedis);
            }
        }
    }

    /**
     * 根据键删除值,批量操作,键不存不操作,返回键值对删除的个数,没有返回0
     *
     * @param keys key 数组
     */
    public static void del(String... keys) {

        Jedis jedis = jedisPool.getResource();
        try {
            jedis.del(keys);
        } catch (Exception e) {
            logger.error(e, e);
            jedisPool.returnBrokenResource(jedis);
            jedis = null;
            throw e;
        } finally {
            if (jedis != null) {
                jedisPool.returnResource(jedis);
            }
        }
    }

    /**
     * 删除 匹配的 key 对应的数据
     *
     * @param pattern
     */
    public static void delPattern(String pattern) {
        Jedis jedis = jedisPool.getResource();
        try {
            Set<String> keys = jedis.keys(pattern);
            if (keys != null && keys.size() > 0) {
                Iterator<String> it = keys.iterator();
                while (it.hasNext()) {
                    String key = it.next();
                    jedis.del(key);
                }
            }
        } catch (Exception e) {
            logger.error(e, e);
            jedisPool.returnBrokenResource(jedis);
            jedis = null;
            throw e;
        } finally {
            if (jedis != null) {
                jedisPool.returnResource(jedis);
            }
        }
    }

    public static boolean exists(String key) {

        Jedis jedis = jedisPool.getResource();
        try {
            return jedis.exists(key);
        } catch (Exception e) {
            logger.error(e, e);
            jedisPool.returnBrokenResource(jedis);
            jedis = null;
            throw e;
        } finally {
            if (jedis != null) {
                jedisPool.returnResource(jedis);
            }
        }
    }

    public static void expire(String key, int seconds) {
        Jedis jedis = jedisPool.getResource();
        try {
            jedis.expire(key, seconds);
        } catch (Exception e) {
            logger.error(e, e);
            jedisPool.returnBrokenResource(jedis);
            jedis = null;
            throw e;
        } finally {
            if (jedis != null) {
                jedisPool.returnResource(jedis);
            }
        }
    }

    public static byte[] getBytes(String key) {
        Jedis jedis = jedisPool.getResource();
        try {
            return jedis.get(key.getBytes());
        } catch (Exception e) {
            logger.error(e, e);
            jedisPool.returnBrokenResource(jedis);
            jedis = null;
            throw e;
        } finally {
            if (jedis != null) {
                jedisPool.returnResource(jedis);
            }
        }
    }

    public static void setBytes(String key, byte[] value, int expire) {
        Jedis jedis = jedisPool.getResource();
        try {
            jedis.setex(key.getBytes(), expire, value);
        } catch (Exception e) {
            logger.error(e, e);
            jedisPool.returnBrokenResource(jedis);
            jedis = null;
            throw e;
        } finally {
            if (jedis != null) {
                jedisPool.returnResource(jedis);
            }
        }
    }

3. set 封装


    /**
     * 将指定的成员添加到key对应的set中。如果成员已是集合的成员,则不执行任何操作。
     * 如果key不存在,则创建一个新的集,其中指定的成员为唯一成员。
     * 如果key存在但不包含设置值,则返回错误。
     *
     * @param key     键
     * @param members 放入set集合的成员数组(值)
     */
    public static void sadd(final String key, final String... members) {
        Jedis jedis = jedisPool.getResource();
        try {
            jedis.sadd(key, members);
        } catch (Exception e) {
            logger.error(e, e);
            jedisPool.returnBrokenResource(jedis);
            jedis = null;
            throw e;
        } finally {
            if (jedis != null) {
                jedisPool.returnResource(jedis);
            }
        }
    }

    /**
     * 如果成员是存储在键上的集合的成员,则返回1,否则返回0。
     *
     * @param key    键
     * @param member 元素值
     * @return true 键对应的list包含member,false不包含
     */
    public static Boolean sismember(final String key, final String member) {
        Jedis jedis = jedisPool.getResource();
        try {
            return jedis.sismember(key, member);
        } catch (Exception e) {
            logger.error(e, e);
            jedisPool.returnBrokenResource(jedis);
            jedis = null;
            throw e;
        } finally {
            if (jedis != null) {
                jedisPool.returnResource(jedis);
            }
        }
    }

    /**
     * 从key 对应的set集合中随意删除一个元素,并返回给对象,如果redis中没有该key,返回null
     *
     * @param key redis的一个key
     * @return string value
     */
    public static String spop(final String key) {

        // 获取jedis
        Jedis jedis = jedisPool.getResource();
        try {
            return jedis.spop(key);
        } catch (Exception e) {
            logger.error(e, e);
            jedisPool.returnBrokenResource(jedis);
            jedis = null;
            throw e;
        } finally {
            if (jedis != null) {
                jedisPool.returnResource(jedis);
            }
        }
    }

    /**
     * 设置key-value;key之前不存在,设置key-value,返回true;key已经存在,不操作,返回false
     *
     * @param key   键
     * @param value 值
     * @return true :key之前不存在,设置key-value;false:key已经存在,不操作
     */
    public static Boolean setnx(final String key, final String value) {
        Jedis jedis = jedisPool.getResource();
        try {
            // jedis.setnx(key,value):如果key已经存在,不设置value,返回0;key不存在,重新设置value,返回1;
            return jedis.setnx(key, value) == 1;
        } catch (Exception e) {
            logger.error(e, e);
            jedisPool.returnBrokenResource(jedis);
            jedis = null;
            throw e;
        } finally {
            if (jedis != null) {
                jedisPool.returnResource(jedis);
            }
        }
    }

4. hash 封装

    /**
     * string-key,string-value
     *
     * @param key     hash-key
     * @param field   hashKey 对应的字段名称
     * @param seconds 设置过期时间
     * @param clazz   value数据类型
     * @return 返回 数据对象
     */
    public static <T> T hget(String key, String field, int seconds, Class<T> clazz) {
        Jedis jedis = jedisPool.getResource();
        try {
            String str = jedis.hget(key, field);
            if (!StringUtils.isEmpty(str)) {
                jedis.expire(key, seconds);
                return JSON.parseObject(JSON.toJSONString(str), clazz);
            }
            return null;
        } catch (Exception e) {
            logger.error(e, e);
            jedisPool.returnBrokenResource(jedis);
            jedis = null;
            throw e;
        } finally {
            if (jedis != null) {
                jedisPool.returnResource(jedis);
            }
        }
    }
Logo

欢迎加入 MCP 技术社区!与志同道合者携手前行,一同解锁 MCP 技术的无限可能!

更多推荐