1. 程式人生 > 實用技巧 >Redis連線操作工具類

Redis連線操作工具類

在開發過程中使用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"); } }