redis的一个工具类(提供了Redis连接池功能和常用的Redis命令操作)

package com.leng.demo.utils;

import org.apache.commons.codec.binary.Base64;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.Transaction;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.*;


/**
 * Redis 工具类,提供了Redis连接池功能和常用的Redis命令操作
 */
public class RedisUtil {
    private static JedisPool jedisPool = null;

    /**
     * 初始化Redis连接池
     *
     * @param host     Redis服务器主机名
     * @param port     Redis服务器端口号
     * @param password Redis服务器密码
     * @param maxTotal 连接池最大连接数
     * @param maxIdle  连接池最大空闲连接数
     * @param maxWait  连接池获取连接时的最大等待毫秒数
     */
    public static void initPool(String host, int port, String password, int maxTotal, int maxIdle, long maxWait) {
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(maxTotal);
        config.setMaxIdle(maxIdle);
        config.setMaxWaitMillis(maxWait);
        if (password != null && password.trim().length() > 0) {
            jedisPool = new JedisPool(config, host, port, 3000, password);
        } else {
            jedisPool = new JedisPool(config, host, port, 3000);
        }
    }

    /**
     * 获取 Redis 连接
     *
     * @return 返回 Redis 连接对象
     */
    public static Jedis getJedis() {
        if (jedisPool == null) {
            return null;
        }
        try {
            return jedisPool.getResource();
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 关闭 Redis 连接
     *
     * @param jedis Redis 连接对象
     */
    public static void closeJedis(Jedis jedis) {
        if (jedis != null) {
            jedis.close();
        }
    }

    // ======== 常用 Redis 命令操作 ==================

    /**
     * 存储数据到Redis中
     *
     * @param key   键名
     * @param value 值
     * @return 如果存储成功返回OK,否则返回null
     */
    public static String set(String key, String value) {
        Jedis jedis = null;
        try {
            jedis = getJedis();
            return jedis.set(key, value);
        } finally {
            closeJedis(jedis);
        }
    }

    /**
     * 获取Redis中的数据
     *
     * @param key 键名
     * @return 返回键名对应的值,如果查询不到则返回null
     */
    public static String get(String key) {
        Jedis jedis = null;
        try {
            jedis = getJedis();
            return jedis.get(key);
        } finally {
            closeJedis(jedis);
        }
    }

    /**
     * 删除Redis中的数据
     *
     * @param key 键名
     * @return 返回删除的个数,如果失败返回0
     */
    public static long del(String key) {
        Jedis jedis = null;
        try {
            jedis = getJedis();
            return jedis.del(key);
        } finally {
            closeJedis(jedis);
        }
    }

    /**
     * 判断Redis中是否存在指定的键名
     *
     * @param key 键名
     * @return 如果存在则返回true,否则返回false
     */
    public static boolean exists(String key) {
        Jedis jedis = null;
        try {
            jedis = getJedis();
            return jedis.exists(key);
        } finally {
            closeJedis(jedis);
        }
    }

    /**
     * 设置Redis中指定键名的过期时间
     *
     * @param key    键名
     * @param expire 过期时间,单位为秒
     * @return 如果成功则返回1,否则返回0
     */
    public static long expire(String key, int expire) {
        Jedis jedis = null;
        try {
            jedis = getJedis();
            return jedis.expire(key, expire);
        } finally {
            closeJedis(jedis);
        }
    }

    /**
     * 将对象序列化为字符串
     *
     * @param obj 待序列化对象
     * @return 序列化后的字符串
     */
    public static String serialize(Object obj) {
        if (obj == null) {
            return null;
        }
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeObject(obj);
            byte[] bytes = baos.toByteArray();
            return Base64.encodeBase64String(bytes);
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }


    /**
     * 将数据插入 Redis 列表头部
     *
     * @param key   键名
     * @param value 值
     */
    public static void lpush(String key, Object value) {
        Jedis jedis = null;
        try {
            jedis = getJedis();
            jedis.lpush(key.getBytes(), SerializeUtil.serialize(value));
        } finally {
            closeJedis(jedis);
        }
    }

    /**
     * 将数据插入 Redis 列表尾部
     *
     * @param key   键名
     * @param value 值
     */
    public static void rpush(String key, Object value) {
        Jedis jedis = null;
        try {
            jedis = getJedis();
            jedis.rpush(key.getBytes(), SerializeUtil.serialize(value));
        } finally {
            closeJedis(jedis);
        }
    }

    /**
     * 获取 Redis 列表中指定区间的元素
     *
     * @param key   键名
     * @param start 起始下标(包含)
     * @param end   结束下标(包含)
     * @return Redis 列表中指定区间的元素,如果查询失败则返回 null
     */
    public static List<Object> lrange(String key, long start, long end) {
        Jedis jedis = null;
        try {
            jedis = getJedis();
            List<byte[]> list = jedis.lrange(key.getBytes(), start, end);
            if (list == null || list.size() == 0) {
                return null;
            }
            List<Object> result = new ArrayList<>();
            for (byte[] data : list) {
                result.add(SerializeUtil.unserialize(data));
            }
            return result;
        } finally {
            closeJedis(jedis);
        }
    }

    /**
     * 将数据存储到 Redis 字典中
     *
     * @param key 键名
     * @param map 数据键值对
     * @return 如果存储成功返回OK,否则返回null
     */
    public static String hmset(String key, Map<String, Object> map) {
        Jedis jedis = null;
        try {
            jedis = getJedis();
            Map<byte[], byte[]> newMap = new HashMap<>();
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                newMap.put(entry.getKey().getBytes(), SerializeUtil.serialize(entry.getValue()));
            }
            return jedis.hmset(key.getBytes(), newMap);
        } finally {
            closeJedis(jedis);
        }
    }

    /**
     * 从 Redis 字典中获取指定键名的数据
     *
     * @param key       键名
     * @param fieldKeys 字段名数组
     * @return 返回 Redis 字典中指定键名和字段名的数据,如果查询失败则返回 null
     */
    public static List<Object> hmget(String key, String... fieldKeys) {
        Jedis jedis = null;
        try {
            jedis = getJedis();
            byte[][] fields = new byte[fieldKeys.length][];
            for (int i = 0; i < fieldKeys.length; i++) {
                fields[i] = fieldKeys[i].getBytes();
            }
            List<byte[]> dataList = jedis.hmget(key.getBytes(), fields);
            if (dataList == null || dataList.size() == 0) {
                return null;
            }
            List<Object> result = new ArrayList<>();
            for (byte[] data : dataList) {
                result.add(SerializeUtil.unserialize(data));
            }
            return result;
        } finally {
            closeJedis(jedis);
        }
    }

    /**
     * 获取 Redis 字典中的所有数据
     *
     * @param key 键名
     * @return 返回 Redis 字典中的所有数据,如果查询失败则返回 null
     */
    public static Map<String, Object> hgetAll(String key) {
        Jedis jedis = null;
        try {
            jedis = getJedis();
            Map<byte[], byte[]> map = jedis.hgetAll(key.getBytes());
            if (map == null || map.size() == 0) {
                return null;
            }
            Map<String, Object> result = new HashMap<>();
            for (Map.Entry<byte[], byte[]> entry : map.entrySet()) {
                String field = new String(entry.getKey());
                Object value = SerializeUtil.unserialize(entry.getValue());
                result.put(field, value);
            }
            return result;
        } finally {
            closeJedis(jedis);
        }
    }

    /**
     * Redis 事务操作,支持多个命令同时执行
     *
     * @param commands Redis 命令数组,每个元素为一个字符串数组,第一个元素为 Redis 命令名称,后面的元素分别表示该命令所需的参数
     * @return 如果所有命令执行成功则返回每个命令的执行结果,否则返回 null
     */
    public static List<Object> transaction(List<String[]> commands) {
        Jedis jedis = null;
        try {
            jedis = getJedis();
            Transaction transaction = jedis.multi();
            for (String[] command : commands) {
                String name = command[0];
                String[] args = Arrays.copyOfRange(command, 1, command.length); // 截取参数数组中除第一个元素以外的部分
                transaction.getClass().getDeclaredMethod(name, String[].class).invoke(transaction, new Object[]{args}); // 动态调用 Redis Transaction 对象的方法
            }
            return transaction.exec();
        } catch (Exception e) {
            return null;
        } finally {
            closeJedis(jedis);
        }
    }

    /**
     * 获取 Redis 指定键名的剩余生存时间
     *
     * @param key 键名
     * @return 返回剩余生存时间(单位秒),如果查询失败或者键不存在则返回-2,如果该键没有设置过期时间则返回-1。
     */
    public static long ttl(String key) {
        Jedis jedis = null;
        try {
            jedis = getJedis();
            return jedis.ttl(key.getBytes());
        } finally {
            closeJedis(jedis);
        }
    }

    /**
     * 获取Redis中所有匹配指定前缀的键名
     *
     * @param prefix 前缀
     * @return 匹配的键名集合
     */
    public static Set<String> getKeysByPrefix(String prefix) {
        Set<String> keys = null;
        Jedis jedis = null;
        try {
            jedis = getJedis();
            if (jedis != null) {
                keys = jedis.keys(prefix + "*");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            close(jedis);
        }
        return keys;
    }

    private static void close(Jedis jedis) {
        if (jedis != null) {
            jedis.close();
        }
    }

    /**
     * 执行事务操作
     *
     * @param key 键
     * @return 事务执行结果
     */
    public static List<Object> transaction(String key) {
        Jedis jedis = null;
        try {
            jedis = getJedis();
            if (jedis != null) {
                Transaction tx = jedis.multi();
                tx.incr(key);
                tx.decr(key);
                return tx.exec();
            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            close(jedis);
        }
    }

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 编写Redis cluster连接池需要使用Java客户端,例如Jedis,Lettuce等,并使用连接池管理器来管理连接。具体的实现可以参考Redisson的源码,它是一个开源的Redis Java连接池库。 ### 回答2: RedisCluster是Redis一个集群模式,它以分布式的方式存储数据,并提供高可用性和性能的读写操作。在使用Java连接RedisCluster时,可以使用JedisCluster对象进行连接管理并操作Redis集群。 下面是一个简单的示例,展示如何使用Java编写一个RedisCluster连接池: 1. 首先,我们需要在pom.xml中添加Jedis依赖: ```xml <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>3.10.0</version> </dependency> ``` 2. 创建RedisCluster连接池对象。可以使用Apache Commons Pool来实现一个连接池,用于管理连接的复用和分配等操作: ```java import org.apache.commons.pool2.impl.GenericObjectPool; import org.apache.commons.pool2.impl.GenericObjectPoolConfig; import redis.clients.jedis.HostAndPort; import redis.clients.jedis.JedisCluster; import redis.clients.jedis.JedisPoolConfig; import java.util.HashSet; import java.util.Set; public class RedisClusterConnectionPool { private static final String HOST = "127.0.0.1"; private static final int PORT = 6379; private static final int CONNECTION_TIMEOUT = 2000; private static final int MAX_TOTAL_CONNECTIONS = 10; private static final int MAX_IDLE_CONNECTIONS = 5; private static final int MIN_IDLE_CONNECTIONS = 1; private static final long MAX_WAIT_TIME = 2000; private JedisCluster jedisCluster; public RedisClusterConnectionPool() { Set<HostAndPort> jedisClusterNodes = new HashSet<>(); jedisClusterNodes.add(new HostAndPort(HOST, PORT)); // 配置连接池 GenericObjectPoolConfig<JedisCluster> poolConfig = new JedisPoolConfig(); poolConfig.setMaxTotal(MAX_TOTAL_CONNECTIONS); poolConfig.setMaxIdle(MAX_IDLE_CONNECTIONS); poolConfig.setMinIdle(MIN_IDLE_CONNECTIONS); poolConfig.setMaxWaitMillis(MAX_WAIT_TIME); // 创建连接池 GenericObjectPool<JedisCluster> connectionPool = new GenericObjectPool<>(new RedisClusterConnectionFactory(jedisClusterNodes), poolConfig); // 从连接池获取JedisCluster对象 try { jedisCluster = connectionPool.borrowObject(); } catch (Exception e) { e.printStackTrace(); } } } ``` 3. 创建RedisClusterConnectionFactory类,用于创建JedisCluster连接: ```java import org.apache.commons.pool2.PooledObject; import org.apache.commons.pool2.PooledObjectFactory; import org.apache.commons.pool2.impl.DefaultPooledObject; import redis.clients.jedis.HostAndPort; import redis.clients.jedis.JedisCluster; import java.util.Set; public class RedisClusterConnectionFactory implements PooledObjectFactory<JedisCluster> { private Set<HostAndPort> jedisClusterNodes; public RedisClusterConnectionFactory(Set<HostAndPort> jedisClusterNodes) { this.jedisClusterNodes = jedisClusterNodes; } @Override public PooledObject<JedisCluster> makeObject() throws Exception { return new DefaultPooledObject<>(new JedisCluster(jedisClusterNodes)); } @Override public void destroyObject(PooledObject<JedisCluster> p) throws Exception { p.getObject().close(); } @Override public boolean validateObject(PooledObject<JedisCluster> p) { return p.getObject().isConnected(); } @Override public void activateObject(PooledObject<JedisCluster> p) throws Exception { } @Override public void passivateObject(PooledObject<JedisCluster> p) throws Exception { } } ``` 以上就是一个使用Java编写的RedisCluster连接池的基本实现。通过这个连接池,我们可以方便地获取并管理RedisCluster的连接对象,以便进行各种读写操作。同时,连接池提供了连接复用、性能优化等功能,提高了系统的可靠性和性能。 ### 回答3: Java RedisCluster连接池一个用于管理Redis集群连接的工具,用于提高连接的复用性和性能。 首先,我们需要引入redis.clients.jedis.JedisCluster类作为Redis集群连接的核心类,并在项目中引入Jedis库。 接下来,我们可以创建一个RedisClusterPool类,该类包含以下几个主要方法: 1. 初始化连接池:在初始化方法中,我们可以通过配置文件或硬编码方式获取Redis集群的主机地址、端口号等信息,并创建一个连接池对象。在连接池对象中,我们可以设置最大连接数、最大空闲连接数、连接超时时间等参数。 2. 获取连接:通过getConnection方法,我们可以从连接池中获取一个可用的Redis连接。连接池管理多个连接对象,并根据需要进行创建、销毁和维护。 3. 释放连接:使用完Redis连接后,我们需要将连接释放回连接池,以供其他线程使用。通过releaseConnection方法,我们可以将连接归还到连接池中。 4. 关闭连接池:在程序结束时,需要显式地关闭连接池,以释放连接池所占用的资源。通过closePool方法,我们可以关闭连接池,并释放所有连接。 此外,我们还可以增加一些辅助方法,用于检查连接是否可用、重连失败的连接等。 使用Java编写RedisCluster连接池的好处是,可以有效地管理和复用Redis连接,提高系统性能和稳定性。同时,连接池可以减少重复创建和销毁连接的开销,并可以根据实际需求自动调整连接的创建和回收策略,提供更好的连接资源管理。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值