RedisUtil,總結使用Redis的工具類


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"));
    } 
    
    
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM