Redis获取数据

package com.mvs.monitor.utils;

import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

public class RedisUtils {
    private static JedisPool jedisPool = null;
    // Redis服务器IP
    private static String IP;
    // Redis的端口号
    private static int PORT;
    // 访问密码
    private static String AUTH;
    // 日志对象
    private static Logger log = LoggerFactory.getLogger(RedisUtils.class);
    

    private static final String SUCCESS = "OK";
    private static final String SET_IF_NOT_EXIST = "NX";
    private static final String SET_WITH_EXPIRE_TIME = "PX";
    private static final Long SUCCESS_RETRUN = 1L;
    /**
     * 初始化Redis连接池
     */
    static {
        try {
            jedisPool = getPool();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // /**
    // * 设置对象
    // *
    // * @param key
    // * @param obj
    // */
    // public static void setObject(String key, Object obj) {
    // try {
    // obj = obj == null ? new Object() : obj;
    // getJedis().set(key.getBytes(), SerializeUtil.serialize(obj));
    // } catch (Exception e) {
    // e.printStackTrace();
    // }
    // }
    //
    // /**
    // * 获取对象
    // *
    // * @param key
    // * @return Object
    // */
    // public static Object getObject(String key) {
    // if (getJedis() == null || !getJedis().exists(key)) {
    // return null;
    // }
    // byte[] data = getJedis().get(key.getBytes());
    // return (Object) SerializeUtil.unserialize(data);
    // }
    public static JedisPool getPool() {
        try {
            IP = PUtils.getString("redis.host");
            PORT = Integer.parseInt(PUtils.getString("redis.port"));
            AUTH = PUtils.getString("redis.auth");
            log.debug("RedisHost:" + IP);
            log.debug("RedisPort:" + PORT);
            log.debug("RedisAuth:" + AUTH);
            JedisPoolConfig config = new JedisPoolConfig();
            // 连接耗尽时是否阻塞, false报异常,ture阻塞直到超时, 默认true
            config.setBlockWhenExhausted(true);
            // 设置的逐出策略类名, 默认DefaultEvictionPolicy(当连接超过最大空闲时间,或连接数超过最大空闲连接数)
            config.setEvictionPolicyClassName("org.apache.commons.pool2.impl.DefaultEvictionPolicy");
            // 是否启用pool的jmx管理功能, 默认true
            config.setJmxEnabled(true);
            // 最大空闲连接数, 默认8个 控制一个pool最多有多少个状态为idle(空闲的)的jedis实例。
            config.setMaxIdle(50);
            // 最大连接数, 默认8个
            config.setMaxTotal(300);
            // 表示当borrow(引入)一个jedis实例时,最大的等待时间,如果超过等待时间,则直接抛出JedisConnectionException;
            config.setMaxWaitMillis(1000 * 100);
            // 在borrow一个jedis实例时,是否提前进行validate操作;如果为true,则得到的jedis实例均是可用的;
            config.setTestOnBorrow(true);
            if (StringUtils.isEmpty(AUTH)) {
                jedisPool = new JedisPool(config, IP, PORT, 3000);
            } else {
                jedisPool = new JedisPool(config, IP, PORT, 3000, AUTH);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jedisPool;
    }

    /**
     * 获取Jedis实例 Utilindex:redis节点
     * 
     * @param String
     *            utilIndex
     *            若为null 或者 空时, 使用默认配置节点
     * @author Frank.fang
     */
    private synchronized static Jedis getJedis(String utilIndex) {
        Jedis resource = null;
        try {
            if (jedisPool == null) {
                jedisPool = getPool();
            }
            resource = jedisPool.getResource();
            if (StringUtils.isBlank(utilIndex)) {
                utilIndex = PUtils.getString("redis.templates.index");
            }
            resource.select(Integer.valueOf(utilIndex));
            return resource;
        } catch (Exception e) {
            e.printStackTrace();
            if (resource != null && jedisPool != null) {
                resource.close();
                jedisPool.close();
//                jedisPool.returnBrokenResource(resource);
            }
            return null;
        }
    }

    public  synchronized static Jedis getJedisForScan(String utilIndex) {
        return getJedis();
    }
       
    public  synchronized static Jedis getJedisForScan() {
        return getJedis(null);
    }
    
    /**
     * 返回默认库的jedis
     * 
     * @return
     */
    private synchronized static Jedis getJedis() {
        return getJedis(null);
    }

    /**
     * 释放jedis资源
     * 
     * @param jedis
     */
    private static void close(final Jedis jedis) {
        if (jedis != null) {
            jedis.close();
        }
    }

    public static void closeForScan(final Jedis jedis) {
        close(jedis);
    }    

    /**
     * 字符串测试
     * 
     * @param jedis
     */
    public static void testString(Jedis jedis) {
        jedis.set("name", "xxxx");// 向key-->name中放入了value-->xinxin
        log.debug(jedis.get("name"));// 执行结果:xinxin
        jedis.append("name", " is my lover"); // 拼接
        log.debug(jedis.get("name"));
        jedis.del("name"); // 删除某个键
        log.debug(jedis.get("name"));
        // 设置多个键值对
        jedis.mset("name", "某某某", "age", "24", "qq", "476777XXX");
        jedis.incr("age"); // 进行加1操作
        log.debug(jedis.get("name") + "-" + jedis.get("age") + "-" + jedis.get("qq"));
    }

    public static void saveJsonStr(String index, String key, String strjson) {
        Jedis jedis = null;
        try {
            jedis = RedisUtils.getJedis(index);
            jedis.set(key, strjson);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            close(jedis);
        }
    }

    public static void saveJsonStr(String key, String strjson) {
        saveJsonStr(null, key, strjson);
    }

    public static String saveJsonMap(String index, String key, Map<String, String> mapjson) {
        String ret = null;
        Jedis jedis = null;
        try {
            jedis = RedisUtils.getJedis(index);
            ret = jedis.hmset(key, mapjson);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            close(jedis);
        }
        return ret;
    }

    public static String saveJsonMap(String key, Map<String, String> mapjson) {
        return saveJsonMap(null, key, mapjson);
    }

    public static Map<String, String> getJsonMap(String index, String key) {
        Jedis jedis = null;
        Map<String, String> ret = null;
        try {
            jedis = RedisUtils.getJedis(index);
            ret = jedis.hgetAll(key);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            close(jedis);
        }
        return ret;
    }

    public static Map<String, String> getJsonMap(String key) {
        return getJsonMap(null, key);
    }

    public static ScanResult<Entry<String, String>>  getScanResult(String index, String key,String match) {
        Jedis jedis = null;
        ScanResult<Entry<String, String>>  ret = null;
        try {
            jedis = RedisUtils.getJedis(index);
            ScanParams params = new ScanParams();
            params.count(jedis.hlen(key).intValue()); 
            params.match(match);
            ret = jedis.hscan(key, "0", params);
            
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            close(jedis);
        }
        return ret;
    }
    public static ScanResult<Entry<String, String>>  getScanResult(String key,String match) {
        return getScanResult(null,key,match);
    }
    
    public static Set<String> hkeys(String index, String key) {
        Jedis jedis = null;
        Set<String>   ret = null;
        try {
            jedis = RedisUtils.getJedis(index);
            ret = jedis.hkeys(key);
            
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            close(jedis);
        }
        return ret;
    }
    
    public static Set<String> hkeys(String key) {
        return hkeys(null,key);
    }
    
    public static Map<String, String>  hgetAll(String index, String key) {
        Jedis jedis = null;
        Map<String, String>  ret = null;
        try {
            jedis = RedisUtils.getJedis(index);
            ret = jedis.hgetAll(key);
            
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            close(jedis);
        }
        return ret;
    }
    
    public static Map<String, String>  hgetAll(String key) {
        return hgetAll(null,key);
    }
      
    public static List<String>  hmget(String index, String key) {
        Jedis jedis = null;
        List<String>  ret = null;
        try {
            jedis = RedisUtils.getJedis(index);
            ret = jedis.hmget(key);
            
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            close(jedis);
        }
        return ret;
    }
    
    public static List<String>  hmget(String key) {
        return hmget(null,key);
    }
    
    public static List<String>  hmget2(String index, String key1,String key2) {
        Jedis jedis = null;
        List<String>  ret = null;
        try {
            jedis = RedisUtils.getJedis(index);
            ret = jedis.hmget(key1,key2);
            
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            close(jedis);
        }
        return ret;
    }
    
    public static List<String>  hmget2(String key1,String key2) {
        return hmget2(null,key1,key2);
    }
    
    public static List<String>  del(String index, String key) {
        Jedis jedis = null;
        List<String>  ret = null;
        try {
            jedis = RedisUtils.getJedis(index);
            jedis.del(key);
            
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            close(jedis);
        }
        return ret;
    }
    
    
    public static void del(String key) {
        del(null,key);
    }

    
    /***
     * <p>
     * Description: 得到值
     * </p>
     * 
     * @author wenquan
     * @date 2017年1月5日
     * @param key
     */
    public static String get(String index, String key) {
        String value = null;
        Jedis jedis = null;
        try {
            jedis = getJedis(index);
            value = jedis.get(key);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            close(jedis);
        }
        return value;
    }

    public static String get(String key) {
        return get(null,key);
    }
    /***
     * <p>
     * Description: 查看该键还有多少秒过期
     * </p>
     * 
     * @author wenquan
     * @date 2017年1月5日
     * @param key
     *            seconds秒数
     */
    public static Long expire(String index, String key, int seconds) {
        Jedis jedis = null;
        Long res = 0l;
        try {
            jedis = getJedis(index);
            res = jedis.expire(key, seconds);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 返还到连接池
            close(jedis);
        }
        return res;
    }

    public static Long expire(String key, int seconds) {
        return expire(null,key,seconds);
    }
    
    /**
     * map 用法
     * 
     * @param jedis
     */
    public static void testMap(Jedis jedis) {
        // -----添加数据----------
        Map<String, String> map = new HashMap<String, String>();
        map.put("name", "xinxin");
        map.put("age", "22");
        map.put("qq", "123456");
        jedis.hmset("user", map);
        // 取出user中的name,执行结果:[minxr]-->注意结果是一个泛型的List
        // 第一个参数是存入redis中map对象的key,后面跟的是放入map中的对象的key,后面的key可以跟多个,是可变参数
        List<String> rsmap = jedis.hmget("user", "name", "age", "qq");
        log.debug(rsmap.toString());
        // 删除map中的某个键值
        jedis.hdel("user", "age");
        log.debug(jedis.hmget("user", "age").toString()); // 因为删除了,所以返回的是null
        log.debug(jedis.hlen("user").toString()); // 返回key为user的键中存放的值的个数2
        log.debug(jedis.exists("user").toString());// 是否存在key为user的记录 返回true
        log.debug(jedis.hkeys("user").toString());// 返回map对象中的所有key
        log.debug(jedis.hvals("user").toString());// 返回map对象中的所有value
        Iterator<String> iter = jedis.hkeys("user").iterator();
        while (iter.hasNext()) {
            String key = iter.next();
            log.debug(key + ":" + jedis.hmget("user", key));
        }
    }

    /**
     * jedis操作List
     */
    public static void testList(Jedis jedis) {
        // 开始前,先移除所有的内容
        jedis.del("java framework");
        log.debug(jedis.lrange("java framework", 0, -1).toString());
        // 先向key java framework中存放三条数据
        jedis.lpush("java framework", "spring");
        jedis.lpush("java framework", "struts");
        jedis.lpush("java framework", "hibernate");
        // 再取出所有数据jedis.lrange是按范围取出,
        // 第一个是key,第二个是起始位置,第三个是结束位置,jedis.llen获取长度 -1表示取得所有
        log.debug(jedis.lrange("java framework", 0, -1).toString());
        jedis.del("java framework");
        jedis.rpush("java framework", "spring");
        jedis.rpush("java framework", "struts");
        jedis.rpush("java framework", "hibernate");
        log.debug(jedis.lrange("java framework", 0, -1).toString());
    }

    /**
     * jedis操作Set
     */
    public static void testSet(Jedis jedis) {
        // 添加
        jedis.sadd("user", "liuling");
        jedis.sadd("user", "xinxin");
        jedis.sadd("user", "ling");
        jedis.sadd("user", "zhangxinxin");
        jedis.sadd("user", "who");
        // 移除noname
        jedis.srem("user", "who");
        log.debug(jedis.smembers("user").toString());// 获取所有加入的value
        log.debug(jedis.sismember("user", "who").toString());// 判断 who 是否是user集合的元素
        log.debug(jedis.srandmember("user").toString());
        log.debug(jedis.scard("user").toString());// 返回集合的元素个数
    }

    public static void setMap(String key, Map<String, String> map) {
        try {
            Jedis jedis = RedisUtils.getJedis();
            jedis.select(15);
            jedis.hmset(key, map);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 操作指定的hset
     * @param index
     * @param key
     * @param value - JSONStr
     * 
     * @return 1: success  0: false
     * 
     * @author Frank
     */
    public static Boolean hsetnx(String index, String key, String field, String value) {
        Jedis jedis = null;
        try {
            jedis = RedisUtils.getJedis(index);
            Long result = jedis.hsetnx(key, field, value);
            if (1L == result)
                return true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            close(jedis);
        }
        return false;
    }
    
    /**
     * 操作获取hget
     * @param index
     * @param key
     * @param field
     * @return JSON Object String
     * 
     * @author Frank
     */
    public static String hgetnx(String index, String key, String field) {
        Jedis jedis = null;
        try {
            jedis = RedisUtils.getJedis(index);
            return jedis.hget(key, field);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            close(jedis);
        }
        return null;
    }
    
    /**
     * 操作删除hdel
     * @param index
     * @param key
     * @param field
     * 
     * @author Frank
     */
    public static void hdelnx(String index, String key, String field) {
        Jedis jedis = null;
        try {
            jedis = RedisUtils.getJedis(index);
            jedis.hdel(key, field);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            close(jedis);
        }
    }
    
    /**
     * 获取分布式锁 (通过Set命令原子级操作,完成判断key是否存在-加锁-设置死锁过期时间-返回)
     * @param index 分布式锁存放DB 
     * @param lockKey 分布式锁Key
     * @param uuid 验证requestid
     * @param expireSecond 过期时间,防止死锁
     * @return 加锁成功 or Not
     * 
     * @author Frank
     */
    public static boolean distributedLock(String index, String lockKey, String uuid, int expireSecond) {
        Jedis jedis = getJedis(index);
        String result = jedis.set(lockKey, uuid, SET_IF_NOT_EXIST, SET_WITH_EXPIRE_TIME, expireSecond);
        
        close(jedis);
        if (SUCCESS.equals(result)) {
            return true;
        }
        return false;
    }
    
    /**
     * 释放分布式锁(Eval命令调用lua脚本,判断uuid是否一致从而在原子级操作层面上完成解锁和拒绝解锁操作)
     * @param index
     * @param lockKey
     * @param uuid
     * @return
     * 
     * @author Frank
     */
    public static boolean releaseDistributedLock(String index, String lockKey, String uuid) {
        Jedis jedis = getJedis(index);
        //lua 脚本
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        Object result = jedis.eval(script, Collections.singletonList(lockKey), Collections.singletonList(uuid));
        
        close(jedis);
        if (SUCCESS_RETRUN.equals(result)) {
            return true;
        }
        return false;
    }
}

 

转载于:https://my.oschina.net/lisc2016/blog/3068552

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值