Redis序列化操作工具-JAVA

原创
2017/02/07 11:27
阅读数 802

以往使用memcached。对于任意缓存的使用操作。

而今喜欢Redis。很多小伙伴用redis直接用字符串、json进行对象存储,然而序列化比较通用且性能高于json。

 故此,封装了一个redis序列化操作工具,希望对小伙伴们有用。

package com.app.server.common.cache;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
/**
 * 缓存管理类
 * 
 * @author Max
 *
 */
@Service
public class TurboCache {

	@Resource
	private JedisPool jedisPool;
	/**
	 * 基础操作 
	 */
	
	
	/**
	 * 查询缓存
	 * 
	 * @param key
	 *            缓存key
	 * @return
	 */
	public Object getCache(String key) {
		Jedis jedis = null;
		try {
			jedis = jedisPool.getResource();
			byte[] bytes = jedis.get(key.getBytes("ISO-8859-1"));
			if (isNullOrEmpty(bytes)) {
				return null;
			}
			return unserialize(bytes);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			if (jedis != null) {
				jedisPool.returnResource(jedis);
			}
		}
	}
	/**
	 * 设置缓存
	 * 
	 * @param key
	 *            缓存key
	 * @param value
	 *            缓存内容
	 * @param timeOut
	 *            缓存超时时间
	 */
	public void setCache(String key, Object value, Integer timeOut) {
		if (isNullOrEmpty(key)) {
			return;
		}
		Jedis jedis = null;
		try {
			jedis = jedisPool.getResource();
			jedis.setex(key.getBytes("ISO-8859-1"), timeOut, serialize(value));
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (jedis != null) {
				jedisPool.returnResource(jedis);
			}
		}
	}
	/**
	 * 设置缓存
	 * 
	 * @param key
	 *            缓存key
	 * @param value
	 *            缓存内容
	 */
	public void setCache(String key, Object value) {
		if (isNullOrEmpty(key)) {
			return;
		}
		Jedis jedis = null;
		try {
			jedis = jedisPool.getResource();
			jedis.set(key.getBytes("ISO-8859-1"), serialize(value));
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (jedis != null) {
				jedisPool.returnResource(jedis);
			}
		}
	}
	/**
	 * 删除缓存
	 * 
	 * @param key
	 *            缓存key
	 */
	public void delCache(String key) {
		if (isNullOrEmpty(key)) {
			return;
		}
		Jedis jedis = null;
		try {
			jedis = jedisPool.getResource();
			jedis.del(key.getBytes("ISO-8859-1"));
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (jedis != null) {
				jedisPool.returnResource(jedis);
			}
		}
	}
	/**
	 * 模糊删除缓存
	 * 
	 * @param key
	 *            缓存key
	 */
	public void delCacheFuzz(String key) {
		if (isNullOrEmpty(key)) {
			return;
		}
		key = MessageFormat.format("{0}*", key);
		Jedis jedis = null;
		try {
			jedis = jedisPool.getResource();
			Set<String> keys = jedis.keys(key);
			for (String tmp : keys) {
				jedis.del(tmp);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (jedis != null) {
				jedisPool.returnResource(jedis);
			}
		}
	}
	/**
	 * 检查key是否存在
	 * 
	 * @param key
	 *            缓存key
	 * @param value
	 *            缓存内容
	 * @param timeOut
	 *            缓存超时时间
	 * @return
	 */
	public Boolean contains(String key) {
		if (isNullOrEmpty(key)) {
			return false;
		}
		Jedis jedis = null;
		try {
			jedis = jedisPool.getResource();
			return jedis.exists(key);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		} finally {
			if (jedis != null) {
				jedisPool.returnResource(jedis);
			}
		}
	}
	/**
	 * 基础操作  end
	 */
	
	
	/**
	 * LIST操作 
	 */
	public void lBeanPush(String key, Object... values) {
		Jedis jedis = null;
		try {
			jedis = jedisPool.getResource();
			for (Object value : values) {
				jedis.rpush(key.getBytes("ISO-8859-1"), serialize(value));
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (jedis != null) {
				jedisPool.returnResource(jedis);
			}
		}
	}

	public Object lBeanProp(String key) {
		Jedis jedis = null;
		try {
			jedis = jedisPool.getResource();
			byte[] bytes = jedis.lpop(key.getBytes("ISO-8859-1"));
			if (isNullOrEmpty(bytes)) {
				return null;
			}
			return unserialize(bytes);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			if (jedis != null) {
				jedisPool.returnResource(jedis);
			}
		}
	}

	public List<?> lBeanPropAll(String key) {
		Jedis jedis = null;
		try {
			jedis = jedisPool.getResource();
			byte[] bytes = jedis.lpop(key.getBytes("ISO-8859-1"));
			if (isNullOrEmpty(bytes)) {
				return null;
			}
			List<Object> objs = new ArrayList<Object>();
			objs.add(unserialize(bytes));
			while (!isNullOrEmpty(bytes)) {
				bytes = jedis.lpop(key.getBytes("ISO-8859-1"));
				if (!isNullOrEmpty(bytes)) {
					objs.add(unserialize(bytes));
				}
			}
			return objs;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			if (jedis != null) {
				jedisPool.returnResource(jedis);
			}
		}
	}

	public Long lBeanCount(String key) {
		Jedis jedis = null;
		try {
			jedis = jedisPool.getResource();
			return jedis.llen(key);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			if (jedis != null) {
				jedisPool.returnResource(jedis);
			}
		}
	}

	

	

	/**
	 * SET操作
	 */
	public void sBeanPush(String key, Object... values) {
		if (isNullOrEmpty(values)) {
			return;
		}
		Jedis jedis = null;
		try {
			jedis = jedisPool.getResource();
			for(Object obj:values){
				jedis.sadd(key.getBytes("ISO-8859-1"), serialize(obj));
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (jedis != null) {
				jedisPool.returnResource(jedis);
			}
		}
	}

	public <T> T sBeanPop(String key) {
		Jedis jedis = null;
		try {
			jedis = jedisPool.getResource();
			byte[] bytes =jedis.spop(key.getBytes("UTF-8"));
			if (isNullOrEmpty(bytes)) {
				return null;
			}
			return unserialize(bytes);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			if (jedis != null) {
				jedisPool.returnResource(jedis);
			}
		}
	}

	public void sDel(String key, String... value) {
		Jedis jedis = null;
		try {
			jedis = jedisPool.getResource();
			jedis.srem(key, value);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (jedis != null) {
				jedisPool.returnResource(jedis);
			}
		}
	}

	public Long sCount(String key) {
		Jedis jedis = null;
		try {
			jedis = jedisPool.getResource();
			return jedis.scard(key);
		} catch (Exception e) {
			e.printStackTrace();
			return 0l;
		} finally {
			if (jedis != null) {
				jedisPool.returnResource(jedis);
			}
		}
	}

	/**
	 * SET操作
	 */
	
	
	/**
	 * MAP操作
	 */
	
	public Map<String, Object> hBeanGetMap(String key) {
		Jedis jedis = null;
		try {
			jedis = jedisPool.getResource();
			Map<byte[], byte[]> byteMap = jedis.hgetAll(key.getBytes("ISO-8859-1"));
			if (isNullOrEmpty(byteMap)) {
				return null;
			}
			Map<String, Object> map = new HashMap<String, Object>();
			for (byte[] tmp : byteMap.keySet()) {
				byte[] bytes = byteMap.get(tmp);
				Object value = null;
				if (!isNullOrEmpty(bytes)) {
					value = unserialize(bytes);
				}
				map.put(new String(tmp), value);
			}
			return map;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			if (jedis != null) {
				jedisPool.returnResource(jedis);
			}
		}
	}

	public <T> T hBeanGet(String key, String fieldName) {
		Jedis jedis = null;
		try {
			jedis = jedisPool.getResource();
			byte[] bytes = jedis.hget(key.getBytes("ISO-8859-1"), fieldName.getBytes("ISO-8859-1"));
			if (isNullOrEmpty(bytes)) {
				return null;
			}
			return unserialize(bytes);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			if (jedis != null) {
				jedisPool.returnResource(jedis);
			}
		}
	}

	public void hBeanPush(String key, String fieldName, Object value) {
		Jedis jedis = null;
		try {
			jedis = jedisPool.getResource();
			jedis.hset(key.getBytes("ISO-8859-1"), fieldName.getBytes("ISO-8859-1"),
					serialize(value));
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (jedis != null) {
				jedisPool.returnResource(jedis);
			}
		}
	}
	public List<?> hBeanGetAll(String key) {
		try {
			Map<byte[], byte[]> maps = hBeanGetAll(key.getBytes("ISO-8859-1"));
			if (isNullOrEmpty(maps)) {
				return null;
			}
			List<Object> list = new ArrayList<Object>();
			for (byte[] tmp : maps.keySet()) {
				byte[] bytes = maps.get(tmp);
				if (isNullOrEmpty(bytes)) {
					continue;
				}
				Object value = unserialize(bytes);
				list.add(value);
			}
			return list;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	private Map<byte[], byte[]> hBeanGetAll(byte[] key) {
		Jedis jedis = null;
		try {
			jedis = jedisPool.getResource();
			return jedis.hgetAll(key);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			if (jedis != null) {
				jedisPool.returnResource(jedis);
			}
		}
	}
	public Set<String> hKeys(String key) {
		Jedis jedis = null;
		try {
			jedis = jedisPool.getResource();
			return jedis.hkeys(key);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			if (jedis != null) {
				jedisPool.returnResource(jedis);
			}
		}
	}


	public Long hCount(String key) {
		Jedis jedis = null;
		try {
			jedis = jedisPool.getResource();
			return jedis.hlen(key);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			if (jedis != null) {
				jedisPool.returnResource(jedis);
			}
		}
	}

	public void hDel(String key, String fieldName) {
		Jedis jedis = null;
		try {
			jedis = jedisPool.getResource();
			jedis.hdel(key, fieldName);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (jedis != null) {
				jedisPool.returnResource(jedis);
			}
		}
	}

	public Boolean hContains(String key, String fieldName) {
		Jedis jedis = null;
		try {
			jedis = jedisPool.getResource();
			return jedis.hexists(key, fieldName);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		} finally {
			if (jedis != null) {
				jedisPool.returnResource(jedis);
			}
		}
	}
	
	/**
	 * MAP操作  end
	 */

	
	
	public static boolean isNullOrEmpty(Object obj) {
		try {
			if (obj == null)
				return true;
			if (obj instanceof CharSequence) {
				return ((CharSequence) obj).length() == 0;
			}
			if (obj instanceof Collection) {
				return ((Collection<?>) obj).isEmpty();
			}
			if (obj instanceof Map) {
				return ((Map<?,?>) obj).isEmpty();
			}
			if (obj instanceof Object[]) {
				Object[] object = (Object[]) obj;
				if (object.length == 0) {
					return true;
				}
				boolean empty = true;
				for (int i = 0; i < object.length; i++) {
					if (!isNullOrEmpty(object[i])) {
						empty = false;
						break;
					}
				}
				return empty;
			}
			return false;
		} catch (Exception e) {
			return true;
		}

	}
	public static byte[] serialize(Object object) throws IOException {
		ObjectOutputStream oos = null;
		ByteArrayOutputStream baos = null;
		// 序列化
		baos = new ByteArrayOutputStream();
		oos = new ObjectOutputStream(baos);
		oos.writeObject(object);
		byte[] bytes = baos.toByteArray();
		oos.close();
		baos.close();
		return bytes;
	}

	@SuppressWarnings("unchecked")
	public static <T> T unserialize(byte[] bytes) throws IOException, ClassNotFoundException {
		ByteArrayInputStream bais = null;
			// 反序列化
			bais = new ByteArrayInputStream(bytes);
			ObjectInputStream ois = new ObjectInputStream(bais);
			bais.close();
			Object obj=ois.readObject();
			ois.close();
			return (T) obj;
	}
}

以下是关于jedis的配置:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee"
	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jpa="http://www.springframework.org/schema/data/jpa"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xsi:schemaLocation="
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
		http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd
		http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
		http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd"
	default-lazy-init="false">

	<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
		<property name="maxTotal" value="500" />
		<property name="maxIdle" value="100" />
		<property name="minIdle" value="25" />
		<property name="maxWaitMillis" value="3000" />
		<property name="testOnBorrow" value="true" />
		<property name="testOnReturn" value="true" />
		<property name="testWhileIdle" value="true" />
		<property name="timeBetweenEvictionRunsMillis" value="30000" />
	</bean>
	 <bean id="jedisPool" class="redis.clients.jedis.JedisPool">
        <constructor-arg index="0" ref="jedisPoolConfig"/>
        <constructor-arg index="1" value="54sb.org"/>
        <constructor-arg index="2" value="16379" type="int"/>
        <constructor-arg index="3" value="10000" type="int"/>
        <constructor-arg index="4" value="123456"/>
    </bean>
</beans>

 

缓存的使用:

@Resource
	TurboCache turboCache;
	public  void cacheTest() {
		String key=CacheFinal.APP_INFO_CACHE;
		AppInfo info=turboCache.getCache(key);
	}

 

展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
打赏
0 评论
2 收藏
0
分享
返回顶部
顶部