需要的jar
工具类
package com.para.redis;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
public class RedisUtils {
private static JedisPool jedisPool = null;
private static String redisConfigFile = "com/test/redis/redis.properties";
//把redis连接对象放到本地线程中
private static ThreadLocal<Jedis> local=new ThreadLocal<Jedis>();
//不允许通过new创建该类的实例
private RedisUtils(){}
/**
* 初始化Redis连接池
*/
/**
* 初始化Redis连接池
*/
public static void initialPool() {
try {
Properties props = new Properties();
//加载连接池配置文件
props.load(RedisUtils.class.getClassLoader().getResourceAsStream(redisConfigFile));
// 创建jedis池配置实例
JedisPoolConfig config = new JedisPoolConfig();
// 设置池配置项值
config.setMaxTotal(Integer.valueOf(props.getProperty("jedis.pool.maxActive")));
config.setMaxIdle(Integer.valueOf(props.getProperty("jedis.pool.maxIdle")));
config.setMaxWaitMillis(Long.valueOf(props.getProperty("jedis.pool.maxWait")));
config.setTestOnBorrow(Boolean.valueOf(props.getProperty("jedis.pool.testOnBorrow")));
config.setTestOnReturn(Boolean.valueOf(props.getProperty("jedis.pool.testOnReturn")));
// 根据配置实例化jedis池
jedisPool = new JedisPool(config, props.getProperty("redis.ip"),
Integer.valueOf(props.getProperty("redis.port")),
Integer.valueOf(props.getProperty("redis.timeout")));
//props.getProperty("redis.passWord"));
System.out.println("线程池被成功初始化");
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 连接redis
* @return
*/
public static Jedis getRedis(){
//Redis对象
Jedis jedis =local.get();
if(jedis==null){
if (jedisPool == null) {
initialPool();
}
jedis = jedisPool.getResource(); //从线程池获取
local.set(jedis);
}
return jedis;
}
/**
* 关闭redis释放资源
*/
public static void closeRedis(){
//从本地线程中获取
Jedis jedis =local.get();
if(jedis!=null){
jedis.close();
}
local.set(null);
}
//关闭redis连接池
public static void closePool(){
if(jedisPool!=null){
jedisPool.close();
}
}
/**
* 存对象以字节码存储
* @param <T>
* @param t 类对象
* @param key key
* @throws Exception
*/
public static<T extends Serializable> void setObjT(T t,String key)throws Exception{
ObjectOutputStream oos = null; //对象输出流
ByteArrayOutputStream bos = null; //内存缓冲流
bos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(bos);
oos.writeObject(t);
byte[] byt = bos.toByteArray();
getRedis().set(key.getBytes(), byt);
bos.close();
oos.close();
closeRedis();
}
/**
* 取对象必须是字节码存储的对象
* @param <T>
* @param key key
* @return
* @throws Exception
*/
public static<T extends Serializable> Object getObjT(String key)throws Exception{
if (key == null || key == "") {
return null;
}
byte[] byt = getRedis().get(key.getBytes());
if (byt == null) {
return null;
}
ObjectInputStream ois = null; //对象输入流
ByteArrayInputStream bis = null; //内存缓冲流
Object obj = null;
bis = new ByteArrayInputStream(byt);
ois = new ObjectInputStream(bis);
obj = ois.readObject();
bis.close();
ois.close();
closeRedis();
return obj;
}
/**
* 判断key是否存在
* @param key
* @return true OR false
*/
public static Boolean exists(String key) throws Exception{
Boolean falg = false;
if (getRedis() == null) {
return falg;
}
falg = getRedis().exists(key);
closeRedis();
return falg;
}
/**
* 通过key判断值得类型
* @param key
*
* @return
*/
public static String getTypeByKey(String key) throws Exception{
String result = null;
if (getRedis() == null) {
return result;
}
result = getRedis().type(key);
closeRedis();
return result;
}
/**
* 根据key删除key
* @param key key
* @return
* @throws Exception
*/
public static Boolean delObjKey(String key) throws Exception {
Boolean flag = false;
if (key == null || key == "") {
return flag;
}
Long code = getRedis().del(key);
closeRedis();
if (code == 1L) {
flag = true;
}
return flag ;
}
/**
* 获取所有key
* @return
* @throws Exception
*/
public static Set<String> getAllKeys() throws Exception {
Set<String> keys = getRedis().keys("*");
closeRedis();
return keys;
}
/**
* 添加String类型的key
* @param key key
* @throws Exception
*/
public static void setObjStr(String key,String value) throws Exception {
getRedis().set(key, value);
closeRedis();
}
/**
* 获取String类型的key的值
* @param key key
* @return
* @throws Exception
*/
public static String getObjStr(String key) throws Exception {
if (key == null || key == "") {
return null;
}
String value = getRedis().get(key);
closeRedis();
return value;
}
/**
* 将集合转换为字符串存储
* @param key key
* @param objList 存储的集合
* @param activeTime 该对象的有效时间,单位为秒 如果为0 不设置过期时间
* @return
*/
public static Boolean setArrayList(String key, List<Object> objList,
Integer activeTime) {
if (objList != null && key != null && key != "") {
// getRedis().set(key, JSONArray.fromObject(objList).toString());
if (activeTime != null && activeTime > 0) {
getRedis().expire(key, activeTime);
}
closeRedis();
return true;
}
return false;
}
/**
* key 设置生存时间,当 key 过期时(生存时间为 0 ),它会被自动删除
* @param key
* @param seconds 以秒为单位
* @return 设置成功返回 1 当 key 不存在或者不能为 key 设置生存时间时返回 0
*/
public static Long expireTime(String key, int seconds) throws Exception {
Long result = null;
if (getRedis() == null) {
return result;
}
result = getRedis().expire(key, seconds);
closeRedis();
return result;
}
/**
* 以秒为单位,返回给定 key 的剩余生存时间(TTL, time to live)
* @param key
* @return 当 key 不存在时,返回 -2
* 当 key 存在但没有设置剩余生存时间时,返回 -1
* 否则,以秒为单位,返回 key 的剩余生存时间
*/
public static Long getExpireTime(String key) throws Exception {
Long result = null;
if (getRedis() == null) {
return result;
}
result = getRedis().ttl(key);
closeRedis();
return result;
}
public static void main(String[] args) throws Exception{
//字节码存对象
/*Gson gson = new Gson();
User user = new User();
user.setAge(17);
user.setName("小白");
User user2 = new User();
setObjStr("user", gson.toJson(user2));
user2 = gson.fromJson(getObjStr("user"), User.class) ; //json转对象
System.out.println("名字:"+user2.getName()+"==========="+"年龄:"+user2.getAge());
List<User> userList = new ArrayList<User>();
userList.add(user2);
userList.add(user);
setObjStr("userList", gson.toJson(userList));
List<User> l = new ArrayList<User>();
l = gson.fromJson(getObjStr("userList"), new TypeToken<List<User>>(){}.getType()) ;//把json转换成list
System.err.println(l.size());
for (User user3 : l) {
System.out.println("名字:"+user3.getName()+"==========="+"年龄:"+user3.getAge());
}
Map<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("name", "小红");
paramMap.put("age", 16);
setObjStr("paramMap", gson.toJson(paramMap));
System.out.println(gson.fromJson(getObjStr("paramMap"), new TypeToken<Map<String, Object>>(){}.getType()) );*/
/*if (user == null) {
System.out.println("获取对象失败,没有对应的key");
}else{
System.out.println("名字:"+user.getName()+"==========="+"年龄:"+user.getAge());
}*/
// 存String
setObjStr("userName", "小李");
System.out.println(getObjStr("userName"));
//删除key
//System.out.println(delObjKey("user"));
//查询所有key
/* Iterator<String> it = getAllKeys().iterator();
while (it.hasNext()) {
System.out.println(it.next());
}*/
//判断key是否存在
//System.out.println(exists("name"));
//通过key获取值的类型
//System.out.println(getTypeByKey("uList"));
//expireTime("name",500);
//System.err.println(getExpireTime("name"));
}
}
redis.properties 文件
redis.ip=192.168.84.128
redis.port=6379
#redis.passWord=test123
redis.timeout=3000
jedis.pool.maxActive=100
jedis.pool.maxIdle=50
jedis.pool.maxWait=1500
jedis.pool.testOnBorrow=true
jedis.pool.testOnReturn=true