欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Redis连接操作工具类

程序员文章站 2024-03-14 14:24:52
...

在开发过程中使用Redis,每个人都写一套,很是不方便,下面奉上RedisUtil工具类,包含获取连接,获取资源,释放资源,String、对象保存、删除等等操作

下面上代码:

package com.jane.framework.redis;

import com.jane.framework.common.util.ConstantsConfigureBean;
import com.jane.framework.common.util.SpringContextUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import redis.clients.jedis.*;

import java.io.*;
import java.util.LinkedHashSet;
import java.util.Properties;
import java.util.Set;

public class JedisUtil {
	
	protected final static Logger logger = Logger.getLogger(JedisUtil.class);

	private final static String HOST = "redis的连接地址";
	// redis连接的端口号
	private final static int PORT = 6379;
	// 可用连接实例的最大数目,默认值为8
	private static int MAX_ACTIVE = 1024;
	// 控制一个pool最多有多少个状态为idle(空闲的)的jedis实例,默认值也是8
	private static int MAX_IDLE = 200;
	// 等待可用连接的最大时间,单位毫秒,默认值为-1,表示永不超时
	// 如果超过等待时间,则直接抛出JedisConnectionException
	private static int MAX_WAIT = 20000;
	private static int TIMEOUT = 10000;
	// 在borrow一个jedis实例时,是否提前进行validate操作,如果为true,则得到的jedis实例均是可用的
	private static boolean TEST_ON_BORROW = true;
	// 过期时间 单位:秒
	private static int EXPIRE_TIME = 18000;
	private static final String TEST = "test";
	private static final String REDIS_PASSWORD = "redis的连接密码";
	private static final String SYSTEM_REDIS = "systemRedis";
	private static final String TEST_REDIS_ADDRESS = "testRedisAddress";
	private static final String TEST_REDIS_PORT = "testRedisPort";
	private static final String TEST_REDIS_PASSWORD = "testRedisPassword";
	
	private static volatile JedisPool jedisPool = null;

	private JedisUtil() {
	}

	/**
	 * 获取连接池
	 * @Author <jane>
	 * @Description
	 * @Date 2020-6-10上午10:18:24
	 * @return
	 * @throws
	 */
	public static JedisPool getJedisPoolInstance() {
		if (null == jedisPool) {
			synchronized (JedisUtil.class) {
				if (null == jedisPool) {
					JedisPoolConfig config = new JedisPoolConfig();
					config.setMaxIdle(MAX_ACTIVE);
					config.setMaxIdle(MAX_IDLE);
					config.setMaxWait(MAX_WAIT);
					config.setTestOnBorrow(TEST_ON_BORROW);
					Properties properties = null;
					try {
						properties = PropertiesLoaderUtils.loadAllProperties("config.properties");
					} catch (IOException e) {
						e.printStackTrace();
					}
					String redisType = properties.getProperty(SYSTEM_REDIS);
					// 判断正式系统或者测试开发系统
					if (TEST.equals(redisType)) {
						// 从spring的配置文件获取,此处可以替换成自己的方式
						ConstantsConfigureBean configureBean = SpringContextUtil.getBean("constants");
						String redisAddress = configureBean.getValue(TEST_REDIS_ADDRESS);
						int redisPort = Integer.parseInt(configureBean.getValue(TEST_REDIS_PORT));
						String redisPassword = configureBean.getValue(TEST_REDIS_PASSWORD);
						jedisPool = new JedisPool(config, redisAddress, redisPort, TIMEOUT, redisPassword);
					} else {
						jedisPool = new JedisPool(config, HOST, PORT, TIMEOUT, REDIS_PASSWORD);
					}
				}
			}
		}
		return jedisPool;
	}

	/**
	 * 释放连接
	 * @Author <jane>
	 * @Description
	 * @Date 2020-6-10上午10:18:44
	 * @param jedisPool
	 * @param jedis
	 * @throws
	 */
	public static void release(JedisPool jedisPool, Jedis jedis) {
		if (null != jedis) {
			jedisPool.returnResourceObject(jedis);
		}
	}
	
	/**
	 * 序列化
	 * @Author <jane>
	 * @Description 
	 * 	如果想将对象存入到redis中,需要将对象序列化
	 * 	对象序列化需要注意:对象实现序列化接口,否则会报错。
	 * 	对象中如果引用了其他的对象,其他的的对象也需要序列化,否则报错。
	 * @Date 2020-6-9下午3:27:33
	 * @param object
	 * @return
	 * @throws
	 */
	public static byte[] serizlize(Object object) {
		ObjectOutputStream objectOutputStream = null;
		ByteArrayOutputStream byteArrayOutputStream = null;
		try {
			byteArrayOutputStream = new ByteArrayOutputStream();
			objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
			objectOutputStream.writeObject(object);
			byte[] bytes = byteArrayOutputStream.toByteArray();
			return bytes;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (null != byteArrayOutputStream) {
					byteArrayOutputStream.close();
				}
				if (null != objectOutputStream) {
					objectOutputStream.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		return null;
	}
	
	/**
	 * 反序列化
	 * @Author <jane>
	 * @Description
	 * 	将redis中存入的对象反序列为程序中可用的对象。
	 * @Date 2020-6-9下午3:32:28
	 * @param bytes
	 * @return
	 * @throws
	 */
	public static Object deserialize(byte[] bytes) {
		ByteArrayInputStream byteArrayInputStream = null;
		ObjectInputStream objectInputStream = null;
		try {
			byteArrayInputStream = new ByteArrayInputStream(bytes);
			objectInputStream = new ObjectInputStream(byteArrayInputStream);
			return objectInputStream.readObject();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (null != byteArrayInputStream) {
					byteArrayInputStream.close();
				}
				if (null != objectInputStream) {
					objectInputStream.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		return null;
	}
	
	/**
	 * 设置string
	 * @Author <jane>
	 * @Description
	 * @Date 2020-6-10上午10:18:58
	 * @param redisKey
	 * @param redisValue
	 * @throws
	 */
	public static void setString(String redisKey, String redisValue) {
		if (StringUtils.isNotEmpty(redisKey)) {
			JedisPool jedisPool = JedisUtil.getJedisPoolInstance();
			Jedis jedis = null;
			try {
				jedis = jedisPool.getResource();
				jedis.watch(redisKey);
				Transaction transaction = jedis.multi();
				transaction.set(redisKey, redisValue);
				transaction.expire(redisKey, EXPIRE_TIME);
				transaction.exec();
				jedis.unwatch();
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				JedisUtil.release(jedisPool, jedis);
			}
		}
	}
	
	/**
	 * 写入redis缓存,并设置过期时间
	 * @Author <jane>
	 * @Description
	 * @Date 2020-7-28上午11:14:33
	 * @param redisKey
	 * @param redisValue
	 * @param expireTime
	 * @throws
	 */
	public static void setString(String redisKey, String redisValue, int expireTime) {
		if (StringUtils.isNotEmpty(redisKey)) {
			JedisPool jedisPool = JedisUtil.getJedisPoolInstance();
			Jedis jedis = null;
			try {
				jedis = jedisPool.getResource();
				jedis.watch(redisKey);
				Transaction transaction = jedis.multi();
				transaction.set(redisKey, redisValue);
				transaction.expire(redisKey, expireTime);
				transaction.exec();
				jedis.unwatch();
			} catch (Exception e) {
				logger.info("写入缓存失败,cause:" + e);
			} finally {
				JedisUtil.release(jedisPool, jedis);
			}
		}
	}

	/**
	 * 设置对象
	 * @Author <jane>
	 * @Description 需要对象实现序列化,否则会报错
	 * @Date 2020-6-10上午10:19:16
	 * @param redisKey
	 * @param redisObject
	 * @throws
	 */
	public static void setObject(String redisKey, Object redisObject) {
		if (StringUtils.isNotEmpty(redisKey)) {
			JedisPool jedisPool = JedisUtil.getJedisPoolInstance();
			Jedis jedis = null;
			try {
				jedis = jedisPool.getResource();
				jedis.watch(redisKey.getBytes());
				Transaction transaction = jedis.multi();
				transaction.set(redisKey.getBytes(), serizlize(redisObject));
				transaction.expire(redisKey, EXPIRE_TIME);
				transaction.exec();
				jedis.unwatch();
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				JedisUtil.release(jedisPool, jedis);
			}
		}
	}
	
	/**
	 * 保存key,并设置超时时间等
	 * @Author <jane>
	 * @Description
	 * @Date 2020-7-28上午11:10:25
	 * @param redisKey
	 * @param redisObject
	 * @param expireTime
	 * @throws
	 */
	public static void setObject(String redisKey, Object redisObject, int expireTime) {
		if (StringUtils.isNotEmpty(redisKey)) {
			JedisPool jedisPool = JedisUtil.getJedisPoolInstance();
			Jedis jedis = null;
			try {
				jedis = jedisPool.getResource();
				jedis.watch(redisKey.getBytes());
				Transaction transaction = jedis.multi();
				transaction.set(redisKey.getBytes(), serizlize(redisObject));
				transaction.expire(redisKey, expireTime);
				transaction.exec();
				jedis.unwatch();
			} catch (Exception e) {
				logger.info("写入缓存失败,cause:" + e);
			} finally {
				JedisUtil.release(jedisPool, jedis);
			}
		}
	}
	
	/**
	 * 获取值
	 * @Author <jane>
	 * @Description
	 * @Date 2020-6-10上午10:19:48
	 * @param redisKey
	 * @return
	 * @throws
	 */
	public static String getString(String redisKey) {
		JedisPool jedisPool = JedisUtil.getJedisPoolInstance();
		Jedis jedis = null;
		String redisValue = "";
		try {
			jedis = jedisPool.getResource();
			boolean existKey = jedis.exists(redisKey);
			if (existKey) { 
				redisValue = jedis.get(redisKey);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			JedisUtil.release(jedisPool, jedis);
		}
		return redisValue;
	}
	
	/**
	 * 获取对象
	 * @Author <jane>
	 * @Description
	 * @Date 2020-6-10上午10:19:54
	 * @param redisKey
	 * @return
	 * @throws
	 */
	public static Object getObject(String redisKey) {
		JedisPool jedisPool = JedisUtil.getJedisPoolInstance();
		Jedis jedis = null;
		Object object = null;
		try {
			jedis = jedisPool.getResource();
			boolean existKey = jedis.exists(redisKey.getBytes());
			if (existKey) {
				byte[] bytes = jedis.get(redisKey.getBytes());
				object = deserialize(bytes);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			JedisUtil.release(jedisPool, jedis);
		}
		return object;
	}
	
	/**
	 * 删除值
	 * @Author <jane>
	 * @Description
	 * @Date 2020-6-10上午10:20:00
	 * @param redisKey
	 * @throws
	 */
	public static void delString(String redisKey) {
		if (StringUtils.isNotEmpty(redisKey)) {
			JedisPool jedisPool = JedisUtil.getJedisPoolInstance();
			Jedis jedis = null;
			try {
				jedis = jedisPool.getResource();
				jedis.del(redisKey);
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				JedisUtil.release(jedisPool, jedis);
			}
		}
	}

	public static Long zadd(String key, double score, String member) {
		JedisPool jedisPool = getJedisPoolInstance();
		Jedis jedis = null;
		try {
			jedis = jedisPool.getResource();
			return jedis.zadd(key, score, member);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			JedisUtil.release(jedisPool, jedis);
		}
		return null;
	}

	public static Set<Tuple> zrangeWithScores(String key, long start, long end) {
		JedisPool jedisPool = getJedisPoolInstance();
		Jedis jedis = null;
		try {
			jedis = jedisPool.getResource();
			return jedis.zrangeWithScores(key, start, end);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			JedisUtil.release(jedisPool, jedis);
		}
		return new LinkedHashSet();
	}

	public static Long zrem(String key, String... members) {
		JedisPool jedisPool = getJedisPoolInstance();
		Jedis jedis = null;
		try {
			jedis = jedisPool.getResource();
			return jedis.zrem(key, members);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			JedisUtil.release(jedisPool, jedis);
		}
		return null;
	}
	
	public static void main(String[] args) {
		JedisUtil.setString("zhaosi2222", "40");
	}

}