码迷,mamicode.com
首页 > 其他好文 > 详细

RedisUtil,总结使用Redis的工具类

时间:2020-04-16 15:24:43      阅读:50      评论:0      收藏:0      [点我收藏+]

标签:plist   serialize   str   conf   工具类   jedis   start   lists   stream   

package com.shd.core.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.shd.core.basebiz.dto.TempData;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public class RedisUtil {

    private static JedisPool jedisPool;// 非切片连接池
    private static String maxTotal = RedisConfig.getProperty("redis.pool.maxTotal", "1000");
    private static String maxIdle = RedisConfig.getProperty("redis.pool.maxIdle", "100");
    private static String minIdle = RedisConfig.getProperty("redis.pool.minIdle", "50");
    private static String maxWaitMillis = RedisConfig.getProperty("redis.pool.maxWaitMillis", "10000");
    private static String testOnBorrow = RedisConfig.getProperty("redis.pool.testOnBorrow", "true");
    private static String testOnReturn = RedisConfig.getProperty("redis.pool.testOnReturn", "true");
    private static String testWhileIdle = RedisConfig.getProperty("redis.pool.testWhileIdle", "true");
    private static String ntper = RedisConfig
            .getProperty("redis.pool.numTestsPerEvictionRun", "50");
    private static String tberm = RedisConfig.getProperty(
            "redis.pool.timeBetweenEvictionRunsMillis","30000");
    private static String ip = RedisConfig.getProperty("redis.ip", "127.0.0.1");
    private static int port = Integer.parseInt(RedisConfig.getProperty("redis.port","6379"));
    private static int timeout = Integer.parseInt(RedisConfig.getProperty(
            "redis.timeout", "10000"));
    /**
     * 初始化连接池
     */
    private static void initialPool() {
        if (jedisPool == null) {
            JedisPoolConfig config = new JedisPoolConfig();
            config.setMaxTotal(Integer.parseInt(maxTotal));
            config.setMaxIdle(Integer.parseInt(maxIdle));
            config.setMinIdle(Integer.parseInt(minIdle));
            config.setMaxWaitMillis(Integer.parseInt(maxWaitMillis));
            config.setTestOnBorrow(Boolean.parseBoolean(testOnBorrow));
            config.setTestOnReturn(Boolean.parseBoolean(testOnReturn));
            config.setTestWhileIdle(Boolean.parseBoolean(testWhileIdle));
            config.setNumTestsPerEvictionRun(Integer.parseInt(ntper));
            config.setTimeBetweenEvictionRunsMillis(Integer.parseInt(tberm));
            jedisPool = new JedisPool(config, ip, port, timeout);
        }
    }

    /**
     * 从池中获取jedis实例
     * @return jedis实例
     */
    private/* synchronized */static Jedis getJedis() throws Exception {
        if (jedisPool == null) {
            initialPool();
        }
        Jedis jedis = null;
        if (jedisPool != null) {
            jedis = jedisPool.getResource();
        }
        return jedis;
    }

    /**
     * 存储字符串
     * @param redisKey 标识符(以“STR-”开头)          
     * @param val 字符串
     */
    public static void setString(String redisKey, String val) {
        Jedis jedis = null;
        try {
            jedis = getJedis();
            jedis.set(redisKey, val);
        } catch (Exception e) {
            returnResource(jedis);
        } finally {
            returnResource(jedis);
        }
    }

    /**
     * 根据标识符获取存储的字符串
     * @param redisKey 标识符
     * @return 存储的字符串
     */
    public static String getString(String redisKey) {
        if (!exists(redisKey)) {
            return null;
        }
        Jedis jedis = null;
        try {
            jedis = getJedis();
            String val = jedis.get(redisKey);
            return val;
        } catch (Exception e) {
            e.printStackTrace();
            returnResource(jedis);
        } finally {
            returnResource(jedis);
        }
        return null;
    }

    /**
     * 存储对象
     * @param redisKey 标识符(以“OBJ-”开头)
     * @param obj 对象(必须序列化,实现Serializable接口)
     */
    public static void setObject(String redisKey, Object obj) {
        Jedis jedis = null;
        try {
            jedis = getJedis();
            getJedis().set(redisKey.getBytes(), serialize(obj));
        } catch (Exception e) {
            returnResource(jedis);
            e.printStackTrace();
        } finally {
            returnResource(jedis);
        }
    }

    /**
     * 根据标识符获取对象
     * @param redisKey 标识符
     * @return 对象(必须序列化,实现Serializable接口)
     */
    public static Object getObject(String redisKey) {
        if (!exists(redisKey)) {
            return null;
        }
        Jedis jedis = null;
        try {
            jedis = getJedis();
            byte[] byt = getJedis().get(redisKey.getBytes());
            Object obj = unserizlize(byt);
            return obj;
        } catch (Exception e) {
            returnResource(jedis);
            e.printStackTrace();
        } finally {
            returnResource(jedis);
        }
        return null;
    }

    /**
     * 存储list集合
     * @param redisKey 标识符(以“LIST-”开头)
     * @param list 集合
     * @param isCover 是否覆盖 
     *         true:覆盖 false:不覆盖,追加数据
     */
    public static void setList(String redisKey, List<Object> list,
            boolean isCover) {
        Jedis jedis = null;
        try {
            jedis = getJedis();
            if (isCover) {
                jedis.del(redisKey);
            }
            for (Object object : list) {
                jedis.rpush(redisKey.getBytes(), serialize(object));
            }
        } catch (Exception e) {
            returnResource(jedis);
            e.printStackTrace();
        } finally {
            returnResource(jedis);
        }
    }

    /**
     * 添加对象到list集合
     * @param redisKey 标识符
     * @param Object 对象
     */
    public static void pushObjectToList(String redisKey, Object object) {
        Jedis jedis = null;
        try {
            jedis = getJedis();
            jedis.rpush(redisKey.getBytes(), serialize(object));
        } catch (Exception e) {
            returnResource(jedis);
            e.printStackTrace();
        } finally {
            returnResource(jedis);
        }
    }
    /**
     * 根据标识符获取List集合
     * @param redisKey 标识符
     * @return list 集合
     */
    public static List<Object> popList(String redisKey) {
        Jedis jedis = null;
        try {
            jedis = getJedis();
            if (!exists(redisKey)) {
                return null;
            }
            List<Object> list = new ArrayList<Object>();
            Long len = jedis.llen(redisKey);
            for (int i = 0; i < len; i++) {
                byte[] byt = jedis.lpop(redisKey.getBytes());
                Object obj = unserizlize(byt);
                list.add(obj);
            }
            return list;
        } catch (Exception e) {
            returnResource(jedis);
            e.printStackTrace();
        } finally {
            returnResource(jedis);
        }
        return null;
    }

    /**
     * 根据标识符获取List集合
     * @param redisKey 标识符
     * @return list集合
     */
    public static List<Object> getList(String redisKey) {
        Jedis jedis = null;
        try {
            jedis = getJedis();
            if (!exists(redisKey)) {
                return null;
            }
            List<Object> list = new ArrayList<Object>();
            Long len = jedis.llen(redisKey);
            for (int i = 0; i < len; i++) {
                byte[] byt = jedis.lindex(redisKey.getBytes(), i);
                Object obj = unserizlize(byt);
                list.add(obj);
            }
            return list;
        } catch (Exception e) {
            returnResource(jedis);
            e.printStackTrace();
        } finally {
            returnResource(jedis);
        }
        return null;
    }

    /**
     * 根据标识符和List集合的下标获取对象
     * @param redisKey 标识符
     * @param index 下标(-1表示最后的下标)
     * @return 对象
     */
    public static Object getListObjectByIndex(String redisKey, int index) {
        Jedis jedis = null;
        try {
            jedis = getJedis();
            if (!exists(redisKey)) {
                return null;
            }
            Long len = jedis.llen(redisKey);
            if (index >= len) {
                return null;
            }
            byte[] byt = jedis.lindex(redisKey.getBytes(), index);
            Object obj = unserizlize(byt);
            return obj;
        } catch (Exception e) {
            returnResource(jedis);
            e.printStackTrace();
            return null;
        } finally {
            returnResource(jedis);
        }

    }
    /**
     * 根据标识符移除头部对象,并获取该对象
     * @param redisKey 标识符
     * @return 对象
     */
    public static Object popListObject(String redisKey) {
        Jedis jedis = null;
        try {
            jedis = getJedis();
            if (!exists(redisKey)) {
                return null;
            }
            byte[] byt = jedis.lpop(redisKey.getBytes());
            Object obj = unserizlize(byt);
            return obj;
        } catch (Exception e) {
            returnResource(jedis);
            e.printStackTrace();
        } finally {
            returnResource(jedis);
        }
        return null;
    }

    /**
     * 根据标识符和List集合的起始位置、结束位置获取对象
     * @param redisKey 标识符
     * @param index 起始位置
     * @param index 结束为止(-1表示最后的位置)
     * @return 对象
     */
    public static List<Object> getListByRegion(String redisKey, int start,
            int end) {
        Jedis jedis = null;
        try {
            jedis = getJedis();
            if (!exists(redisKey)) {
                return null;
            }
            List<Object> resultList = new ArrayList<Object>();
            List<byte[]> list = jedis.lrange(redisKey.getBytes(), start, end);
            for (byte[] byt : list) {
                Object obj = null;
                if (byt != null) {
                    obj = unserizlize(byt);
                }
                resultList.add(obj);
            }
            return resultList;
        } catch (Exception e) {
            returnResource(jedis);
            e.printStackTrace();
        } finally {
            returnResource(jedis);
        }
        return null;
    }

    /**
     * 移除count个object对象
     * @param redisKey 标识符
     */
    public static void delListObjects(String redisKey, Object object) {
        Jedis jedis = null;
        try {
            jedis = getJedis();
            jedis.lrem(redisKey.getBytes(), 1, serialize(object));
        } catch (Exception e) {
            returnResource(jedis);
            e.printStackTrace();
        } finally {
            returnResource(jedis);
        }
    }

    /**
     * 保留区域类的元素,其他的删除
     * @param redisKey 标识符
     * @param start 起始位置
     * @param end 结束位置(-1)
     */
    public static void holdListObjectsInRegion(String redisKey, long start, long end) {
        Jedis jedis = null;
        try {
            jedis = getJedis();
            jedis.ltrim(redisKey.getBytes(), start, end);
        } catch (Exception e) {
            returnResource(jedis);
            e.printStackTrace();
        } finally {
            returnResource(jedis);
        }
    }
    /**
     * 返回List的长度
     * @param redisKey redis标识符
     * @return 长度  key不存在,返回 0
     */
    public static long getListSize(String redisKey){
        Jedis jedis = null;
        try {
            jedis = getJedis();
            return jedis.llen(redisKey);
        } catch (Exception e) {
            returnResource(jedis);
            e.printStackTrace();
        } finally {
            returnResource(jedis);
        }
        return 0l;
    }
    /**
     * 存储Map集合
     * @param redisKey 标识符(以“HASH-”开头)
     * @param map 集合
     * @param isCover 是否覆盖 true:新数据 false:旧数据+新数据
     */
    public static void setHash(String redisKey, Map<String, Object> map,
            boolean isCover) {
        Jedis jedis = null;
        try {
            jedis = getJedis();
            if (isCover) {
                jedis.del(redisKey);
            }
            Map<byte[], byte[]> hash = new HashMap<byte[], byte[]>();
            for (String mapKey : map.keySet()) {
                Object object = map.get(mapKey);
                byte[] byt = serialize(object);
                hash.put(mapKey.getBytes(), byt);
            }
            jedis.hmset(redisKey.getBytes(), hash);
        } catch (Exception e) {
            returnResource(jedis);
            e.printStackTrace();
        } finally {
            returnResource(jedis);
        }
    }

    /**
     * 添加某个键值对到缓存中
     * @param redisKey 缓存的标识符
     * @param mapKey  map的标识符
     * @param object 对象
     */
    public static void addObjectToHash(String redisKey, String mapKey,
            Object object) {
        Jedis jedis = null;
        try {
            jedis = getJedis();
            byte[] byt = serialize(object);
            jedis.hset(redisKey.getBytes(), mapKey.getBytes(), byt);
        } catch (Exception e) {
            returnResource(jedis);
            e.printStackTrace();
        } finally {
            returnResource(jedis);
        }
    }

    /**
     * 根据标识符获取Map集合
     * @param redisKey 标识符
     * @return map集合
     */
    public static Map<String, Object> getHash(String redisKey) {
        Jedis jedis = null;
        try {
            jedis = getJedis();
            if (!exists(redisKey)) {
                return null;
            }
            Map<String, Object> resultMap = new HashMap<String, Object>();
            Map<byte[], byte[]> map = jedis.hgetAll(redisKey.getBytes());
            for (byte[] byt : map.keySet()) {
                String mapKey = new String(byt);
                Object object = unserizlize(map.get(byt));
                resultMap.put(mapKey, object);
            }
            return resultMap;
        } catch (Exception e) {
            returnResource(jedis);
            e.printStackTrace();
        } finally {
            returnResource(jedis);
        }
        return null;
    }

    /**
     * 根据标识符和集合的键获取存储的对象
     * @param redisKey 标识符
     * @param mapKey  集合的键
     * @return map存储的对象
     */
    public static Object getObjectByMapKey(String redisKey, String mapKey) {
        Jedis jedis = null;
        try {
            jedis = getJedis();
            if (!exists(redisKey)) {
                return null;
            }
            List<byte[]> list = jedis.hmget(redisKey.getBytes(),
                    mapKey.getBytes());
            if (list != null && list.size() > 0 && list.get(0) != null) {
                byte[] byt = list.get(0);
                Object object = unserizlize(byt);
                return object;
            }
        } catch (Exception e) {
            returnResource(jedis);
            e.printStackTrace();
        } finally {
            returnResource(jedis);
        }
        return null;
    }

    /**
     * 删除标识符存储的map恐吓中一个或多个键值
     * @param redisKey 标识符
     * @param mapKey map集合的键
     */
    public static void delMapByMapKey(String redisKey, String... mapKey) {
        Jedis jedis = null;
        try {
            jedis = getJedis();
            jedis.hdel(redisKey, mapKey);
        } catch (Exception e) {
            returnResource(jedis);
            e.printStackTrace();
        } finally {
            returnResource(jedis);
        }
    }
    /**
     * 返回Map的长度
     * @param redisKey redis标识符
     * @return 长度  key不存在,返回 0
     */
    public static long getMapSize(String redisKey){
        Jedis jedis = null;
        try {
            jedis = getJedis();
            return jedis.hlen(redisKey);
        } catch (Exception e) {
            returnResource(jedis);
            e.printStackTrace();
        } finally {
            returnResource(jedis);
        }
        return 0l;
    }
    /**
     * 设置数据过多久过期(以最后一次设置为准)
     * @param redisKey redis标识符
     * @param seconds 秒 
     */
    public static void setExpireTime(String redisKey,int seconds){
        Jedis jedis = null;
        try {
            jedis = getJedis();
            jedis.expire(redisKey, seconds);
        } catch (Exception e) {
            returnResource(jedis);
            e.printStackTrace();
        } finally {
            returnResource(jedis);
        }
    }
    /**
     * 获取数据的过期时间
     * @param redisKey redis标识符
     * @return 秒 -1:没设置 -2:数据不存在
     */
    public static Long getExpireTime(String redisKey){
        Jedis jedis = null;
        try {
            jedis = getJedis();
            Long time = jedis.ttl(redisKey);
            return time;
        } catch (Exception e) {
            returnResource(jedis);
            e.printStackTrace();
        } finally {
            returnResource(jedis);
        }
        return null;
    }
    /**
     * 判断标识符的是否存在
     * @param redisKey 标识符
     */
    public static boolean exists(String redisKey) {
        Jedis jedis = null;
        try {
            jedis = getJedis();
            return jedis.exists(redisKey);
        } catch (Exception e) {
            returnResource(jedis);
            e.printStackTrace();
        } finally {
            returnResource(jedis);
        }
        return false;
    }

    /**
     * 删除某些标识符的存储的数据
     * @param redisKey 标识符
     */
    public static void del(String... redisKey) {
        Jedis jedis = null;
        try {
            jedis = getJedis();
            jedis.del(redisKey);
        } catch (Exception e) {
            returnResource(jedis);
            e.printStackTrace();
        } finally {
            returnResource(jedis);
        }
    }

    /**
     * 清空数据
     */
    public static void flush() {
        Jedis jedis = null;
        try {
            jedis = getJedis();
            jedis.flushDB();
        } catch (Exception e) {
            returnResource(jedis);
            e.printStackTrace();
        } finally {
            returnResource(jedis);
        }
    }

    /**
     * 释放资源
     */
    public static void returnResource(Jedis jedis) {
        if (jedis != null) {
            jedis.close();
        }
    }

    /**
     * 对象序列化成字节数组
     * @param obj 对象(必须序列化,实现Serializable接口)
     * @return 字节数组
     */
    private static byte[] serialize(Object obj) {
        ObjectOutputStream obi = null;
        ByteArrayOutputStream bai = null;
        try {
            bai = new ByteArrayOutputStream();
            obi = new ObjectOutputStream(bai);
            obi.writeObject(obj);
            byte[] byt = bai.toByteArray();
            return byt;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 字节数组反序列化成对象
     * @param byt 字节数组
     * @return 对象(必须序列化,实现Serializable接口)
     */
    private static Object unserizlize(byte[] byt) {
        ObjectInputStream oii = null;
        ByteArrayInputStream bis = null;
        bis = new ByteArrayInputStream(byt);
        try {
            oii = new ObjectInputStream(bis);
            Object obj = oii.readObject();
            return obj;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    
    public static void main(String[] args) throws Exception {
        List<Object> list = new ArrayList<Object>();
        for (int i = 1; i < 10001; i++) {
            TempData t = new TempData();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            Date date = sdf.parse("20180119210000");
            date.setSeconds(i);
            t.setCreateTime(date);
            System.out.println(sdf.format(date));
            
            t.setDataContent("temperature,20.00,"+sdf.format(date)
                    +";humidity,85.00,"+sdf.format(date)+";battery,12.67,"
                    +sdf.format(date)+";");
            t.setDataId(168755);
            t.setDataType(0);
            t.setIecTriggerType("010000");
            t.setLogicNodeCode("002_FILTH");
            t.setMdeviceid(800010120001l);
            t.setMobjectid(300020120003l);
            t.setMtypeid(42027846);
            list.add(t);
        }
        RedisUtil.setList("LIST-TEMPDATA-FILTH", list, true);
        System.out.println("数量:"+RedisUtil.getListSize("LIST-TEMPDATA-FILTH"));
    } 
    
    
}

 

RedisUtil,总结使用Redis的工具类

标签:plist   serialize   str   conf   工具类   jedis   start   lists   stream   

原文地址:https://www.cnblogs.com/4AMLJW/p/redisUtils202004161427.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!