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);
}
}
}
redis的一个工具类(提供了Redis连接池功能和常用的Redis命令操作)
于 2023-05-04 11:16:08 首次发布