redis的工具类详细

  1. Java中常用的Redis工具类先是JedisUtil工具类:

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

    /**

    • Redis工具类,封装Jedis操作Redis的基本方法
      */
      public class JedisRedisUtil {

      private static String redisHost = "localhost"; // Redis服务器IP
      private static int redisPort = 6379; // Redis服务器端口号
      private static String redisAuth = null; // Redis服务器密码
      private static int redisTimeout = 5000; // 连接超时时间
      private static int redisMaxIdle = 10; // 最大空闲连接数
      private static int redisMaxTotal = 100; // 最大连接数
      private static int redisMaxWaitMillis = 5000; // 最大等待时间(毫秒)

      private static JedisPool jedisPool = null;

      /**

      • 初始化JedisPool连接池
        */
        static {
        try {
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxTotal(redisMaxTotal);
        jedisPoolConfig.setMaxIdle(redisMaxIdle);
        jedisPoolConfig.setMaxWaitMillis(redisMaxWaitMillis);
        if (redisAuth != null && !redisAuth.isEmpty()) {
        jedisPool = new JedisPool(jedisPoolConfig, redisHost, redisPort, redisTimeout, redisAuth);
        } else {
        jedisPool = new JedisPool(jedisPoolConfig, redisHost, redisPort, redisTimeout);
        }
        } catch (Exception e) {
        e.printStackTrace();
        }
        }

      /**

      • 获取Jedis实例
      • @return Jedis实例
        */
        public synchronized static Jedis getJedis() {
        Jedis jedis = null;
        try {
        if (jedisPool != null) {
        jedis = jedisPool.getResource();
        }
        } catch (Exception e) {
        e.printStackTrace();
        }
        return jedis;
        }

      /**

      • 释放Jedis资源
      • @param jedis Jedis实例
        */
        public static void closeJedis(Jedis jedis) {
        if (jedis != null) {
        jedis.close();
        }
        }

      /**

      • 设置缓存
      • @param key 键
      • @param value 值
      • @return String 缓存结果
        */
        public static String set(String key, String value) {
        String result = null;
        Jedis jedis = null;
        try {
        jedis = getJedis();
        result = jedis.set(key, value);
        } catch (Exception e) {
        e.printStackTrace();
        } finally {
        closeJedis(jedis);
        }
        return result;
        }

      /**

      • 获取缓存
      • @param key 键
      • @return String 值
        */
        public static String get(String key) {
        String result = null;
        Jedis jedis = null;
        try {
        jedis = getJedis();
        result = jedis.get(key);
        } catch (Exception e) {
        e.printStackTrace();
        } finally {
        closeJedis(jedis);
        }
        return result;
        }

      /**

      • 删除缓存
      • @param key 键
      • @return Long 删除的数量
        */
        public static Long del(String key) {
        Long result = null;
        Jedis jedis = null;
        try {
        jedis = getJedis();
        result = jedis.del(key);
        } catch (Exception e) {
        e.printStackTrace();
        } finally {
        closeJedis(jedis);
        }
        return result;
        }

      /**

      • 判断缓存中是否存在指定的key
      • @param key 键
      • @return Boolean 存在返回true,否则返回false
        */
        public static Boolean exists(String key) {
        Boolean result = null;
        Jedis jedis = null;
        try {
        jedis = getJedis();
        result = jedis.exists(key);
        } catch (Exception e) {
        e.printStackTrace();
        } finally {
        closeJedis(jedis);
        }
        return result;
        }

      /**

      • 设置key的缓存超时时间
      • @param key 键
      • @param seconds 超时时间(秒)
      • @return Long 设置成功返回1,否则返回0
        */
        public static Long expire(String key, int seconds) {
        Long result = null;
        Jedis jedis = null;
        try {
        jedis = getJedis();
        result = jedis.expire(key, seconds);
        } catch (Exception e) {
        e.printStackTrace();
        } finally {
        closeJedis(jedis);
        }
        return result;
        }
        }
  2. 这个JedisUtil工具类完成了封装Jedis操作Redis的基本方法,包括以下方法:

  • 初始化JedisPool连接池
  • 获取Jedis实例
  • 释放Jedis资源
  • 设置缓存
  • 获取缓存
  • 删除缓存
  • 判断缓存中是否存在指定的key
  • 设置key的缓存超时时间
  1. 以下是一个基于Lettuce的Redis工具类的示例代码:

    import io.lettuce.core.RedisClient;
    import io.lettuce.core.api.StatefulRedisConnection;
    import io.lettuce.core.api.async.RedisAsyncCommands;
    import io.lettuce.core.api.sync.RedisCommands;
    import io.lettuce.core.cluster.ClusterClientOptions;
    import io.lettuce.core.cluster.ClusterTopologyRefreshOptions;

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

    /**

    • Redis工具类,封装了Lettuce连接池,提供基本的同步和异步操作接口
      */
      public class LettuceRedisUtils {
      private static RedisClient redisClient;
      private static StatefulRedisConnection<String, String> connection;
      private static RedisCommands<String, String> syncCommands;
      private static RedisAsyncCommands<String, String> asyncCommands;

      static {
      // 初始化Redis连接池
      redisClient = RedisClient.create("redis://localhost:6379");
      connection = redisClient.connect();
      syncCommands = connection.sync();
      asyncCommands = connection.async();
      }

      /**

      • 关闭Redis连接池
        */
        public static void close() {
        if (connection != null) {
        connection.close();
        }
        if (redisClient != null) {
        redisClient.shutdown();
        }
        }

      /**

      • 获取Redis连接池
      • @return RedisClient对象
        */
        public static RedisClient getRedisClient() {
        return redisClient;
        }

      /**

      • 获取同步操作接口
      • @return RedisCommands对象
        */
        public static RedisCommands<String, String> getSyncCommands() {
        return syncCommands;
        }

      /**

      • 获取异步操作接口
      • @return RedisAsyncCommands对象
        */
        public static RedisAsyncCommands<String, String> getAsyncCommands() {
        return asyncCommands;
        }

      /**

      • 设置指定key的值
      • @param key 键
      • @param value 值
        */
        public static void set(String key, String value) {
        syncCommands.set(key, value);
        }

      /**

      • 获取指定key的值
      • @param key 键
      • @return 值
        */
        public static String get(String key) {
        return syncCommands.get(key);
        }

      /**

      • 删除指定key
      • @param key 键
        */
        public static void del(String key) {
        syncCommands.del(key);
        }

      /**

      • 批量删除指定key
      • @param keys 键的列表
        */
        public static void del(List<String> keys) {
        syncCommands.del(keys.toArray(new String[keys.size()]));
        }

      /**

      • 判断指定key是否存在
      • @param key 键
      • @return 如果存在返回true,否则返回false
        */
        public static boolean exists(String key) {
        return syncCommands.exists(key) == 1;
        }

      /**

      • 获取指定key的过期时间
      • @param key 键
      • @return 过期时间(秒), 如果key不存在或未设置过期时间返回-1
        */
        public static long ttl(String key) {
        return syncCommands.ttl(key);
        }

      /**

      • 设置指定key的过期时间
      • @param key 键
      • @param timeout 超时时间(秒)
        */
        public static void expire(String key, int timeout) {
        syncCommands.expire(key, timeout);
        }

      /**

      • 获取指定key的类型
      • @param key 键
      • @return key的类型
        */
        public static String type(String key) {
        return syncCommands.type(key).name();
        }

      /**

      • 获取指定pattern匹配的所有key
      • @param pattern 匹配模式
      • @return 键的列表
        */
        public static Set<String> keys(String pattern) {
        return syncCommands.keys(pattern);
        }

      /**

      • 在指定哈希表中设置字段的值
      • @param key 哈希表名
      • @param field 字段名
      • @param value 值
        */
        public static void hset(String key, String field, String value) {
        syncCommands.hset(key, field, value);
        }

      /**

      • 在指定哈希表中获取指定字段的值
      • @param key 哈希表名
      • @param field 字段名
      • @return 字段的值
        */
        public static String hget(String key, String field) {
        return syncCommands.hget(key, field);
        }

      /**

      • 删除指定哈希表中的指定字段
      • @param key 哈希表名
      • @param fields 字段名列表
      • @return 删除的字段数量
        */
        public static long hdel(String key, String... fields) {
        return syncCommands.hdel(key, fields);
        }

      /**

      • 获取指定哈希表中所有的字段和值
      • @param key 哈希表名
      • @return 哈希表中所有的字段和值
        */
        public static Map<String, String> hgetall(String key) {
        return syncCommands.hgetall(key);
        }

      /**

      • 在列表的头部添加一个或多个值
      • @param key 列表名
      • @param value 值的列表
      • @return 列表长度
        */
        public static long lpush(String key, String... value) {
        return syncCommands.lpush(key, value);
        }

      /**

      • 在列表的尾部添加一个或多个值
      • @param key 列表名
      • @param value 值的列表
      • @return 列表长度
        */
        public static long rpush(String key, String... value) {
        return syncCommands.rpush(key, value);
        }

      /**

      • 获取列表的长度
      • @param key 列表名
      • @return 列表长度
        */
        public static long llen(String key) {
        return syncCommands.llen(key);
        }

      /**

      • 获取列表指定范围内的元素
      • @param key 列表名
      • @param start 起始位置(含)
      • @param end 结束位置(含)
      • @return 列表元素的列表
        */
        public static List<String> lrange(String key, int start, int end) {
        return syncCommands.lrange(key, start, end);
        }

      /**

      • 配置Redis Cluster的Topology Refresh选项,启用自动刷新Cluster节点信息的功能
      • @param interval 刷新间隔时间
        */
        public static void enableClusterTopologyRefresh(Duration interval) {
        ClusterTopologyRefreshOptions topologyRefreshOptions = ClusterTopologyRefreshOptions.builder()
        .enablePeriodicRefresh(interval)
        .enableAllAdaptiveRefreshTriggers()
        .build();
        redisClient.setOptions(ClusterClientOptions.builder()
        .topologyRefreshOptions(topologyRefreshOptions)
        .build());
        }
        }
  2. 以上代码实现了基本的Redis操作功能,包括设置和获取值、删除键、判断键是否存在、设置和获取过期时间、获取键的类型、获取所有匹配的键、在哈希表中设置和获取字段值、在列表中添加和获取元素等。以下是各个方法的注释说明:

  • close():关闭Redis连接池
  • getRedisClient():获取RedisClient对象
  • getSyncCommands():获取RedisCommands对象(同步操作接口)
  • getAsyncCommands():获取RedisAsyncCommands对象(异步操作接口)
  • set(String key, String value):设置指定key的值
  • get(String key):获取指定key的值
  • del(String key):删除指定key
  • del(List<String> keys):批量删除指定key
  • exists(String key):判断指定key是否存在
  • ttl(String key):获取指定key的过期时间
  • expire(String key, int timeout):设置指定key的过期时间
  • type(String key):获取指定key的类型
  • keys(String pattern):获取指定pattern匹配的所有key
  • hset(String key, String field, String value):在指定哈希表中设置字段的值
  • hget(String key, String field):在指定哈希表中获取指定字段的值
  • hdel(String key, String... fields):删除指定哈希表中的指定字段
  • hgetall(String key):获取指定哈希表中所有的字段和值
  • lpush(String key, String... value
相关推荐
高兴就好(石1 小时前
DB-GPT部署和试用
数据库·gpt
这孩子叫逆2 小时前
6. 什么是MySQL的事务?如何在Java中使用Connection接口管理事务?
数据库·mysql
Karoku0662 小时前
【网站架构部署与优化】web服务与http协议
linux·运维·服务器·数据库·http·架构
码农郁郁久居人下2 小时前
Redis的配置与优化
数据库·redis·缓存
MuseLss3 小时前
Mycat搭建分库分表
数据库·mycat
Hsu_kk4 小时前
Redis 主从复制配置教程
数据库·redis·缓存
DieSnowK4 小时前
[Redis][环境配置]详细讲解
数据库·redis·分布式·缓存·环境配置·新手向·详细讲解
程序猿小D4 小时前
第二百三十五节 JPA教程 - JPA Lob列示例
java·数据库·windows·oracle·jdk·jpa
Flerken1014 小时前
数据库语言、SQL语言、数据库系统提供的两种语言
数据库·sql·oracle
掘根4 小时前
【网络】高级IO——poll版本TCP服务器
网络·数据库·sql·网络协议·tcp/ip·mysql·网络安全