Redis序列化操作工具

Stella981
• 阅读 442

以往使用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);
    }
点赞
收藏
评论区
推荐文章
blmius blmius
2年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Wesley13 Wesley13
2年前
java将前端的json数组字符串转换为列表
记录下在前端通过ajax提交了一个json数组的字符串,在后端如何转换为列表。前端数据转化与请求varcontracts{id:'1',name:'yanggb合同1'},{id:'2',name:'yanggb合同2'},{id:'3',name:'yang
Jacquelyn38 Jacquelyn38
2年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Stella981 Stella981
2年前
Nginx + lua +[memcached,redis]
精品案例1、Nginxluamemcached,redis实现网站灰度发布2、分库分表/基于Leaf组件实现的全球唯一ID(非UUID)3、Redis独立数据监控,实现订单超时操作/MQ死信操作SelectPollEpollReactor模型4、分布式任务调试Quartz应用
Easter79 Easter79
2年前
Twitter的分布式自增ID算法snowflake (Java版)
概述分布式系统中,有一些需要使用全局唯一ID的场景,这种时候为了防止ID冲突可以使用36位的UUID,但是UUID有一些缺点,首先他相对比较长,另外UUID一般是无序的。有些时候我们希望能使用一种简单一些的ID,并且希望ID能够按照时间有序生成。而twitter的snowflake解决了这种需求,最初Twitter把存储系统从MySQL迁移
Easter79 Easter79
2年前
SpringBoot使用RedisTemplate操作Redis时,key值出现 -xac-xed-x00-x05t-x00-tb
原因分析原因与RedisTemplate源码中的默认序列化方式有关defaultSerializernewJdkSerializationRedisSerializer(classLoader!null?classLoader:this.getClass().getClassLoader()
Stella981 Stella981
2年前
FastJson 反序列化注意事项
问题描述使用fastJson对json字符串进行反序列化时,有几个点需要注意一下:反序列化内部类反序列化模板类0\.Getter/Setter问题如我们希望返回的一个json串为"name":"name","isDeleted":true,"isEmpty":1
Wesley13 Wesley13
2年前
unity将 -u4E00 这种 编码 转汉字 方法
 unity中直接使用 JsonMapper.ToJson(对象),取到的字符串,里面汉字可能是\\u4E00类似这种其实也不用转,服务器会通过类似fastjson发序列化的方式,将json转对象,获取对象的值就是中文但是有时服务器要求将传参中字符串中类似\\u4E00这种转汉字,就需要下面 publ
Python进阶者 Python进阶者
3个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这