redis 存储hash

纵饮孤独 提交于 2019-11-30 13:21:56

这个是项目中用到的我在这里只是做个搬运工,

set  就是普通的已key-value 方式存储数据,可以设置过期时间

散列类型与Java中的HashMap相似,是一组键值对的集合,且支持单独对其中一个键进行增删改查操作

 hash 上单个不适合存储大量的 filed 并且如果 filed 多了比较消耗cpu,但同时以 散列表存储则比较节省内存。

 

1.redis中存hash

        Map<String,String> redisMap = new HashMap<>();
        redisMap.put(RedisCommenKey.UMENG_USER_ONLINE_REDIS_KEY + user.getId(), umToken);

    //13 代表存在哪个数据库中的
        redisUtil.hmset(RedisCommenKey.UMENG_USER_ONLINE_REDIS, redisMap, 13);

再看工具类中怎么用的

/**
     * <p>
     * 通过key同时设置 hash的多个field
     * </p>
     *
     * @param key
     * @param hash
     * @return 返回OK 异常返回null
     */
    public String hmset(String key, Map<String, String> hash, int indexdb) {
        Jedis jedis = null;
        String res = null;
        try {
            jedis = jedisPool.getResource();
            jedis.select(indexdb);
            res = jedis.hmset(key, hash);
        } catch (Exception e) {

            e.printStackTrace();
        } finally {
            returnResource(jedisPool, jedis);
        }
        return res;
    }

 

2.取的时候

 

List<String> hmget = redisUtil.hmget(RedisCommenKey.UMENG_USER_ONLINE_REDIS, 13, keys.toArray(new String[] {}));

 

看工具怎么写

    
    /**
     * <p>
     * 通过key 和 fields 获取指定的value 如果没有对应的value则返回null
     * </p>
     *
     * @param key
     * @param fields
     *            可以使 一个String 也可以是 String数组
     * @return
     */
    public List<String> hmget(String key, int indexdb, String... fields) {
        Jedis jedis = null;
        List<String> res = null;
        try {
            jedis = jedisPool.getResource();
            jedis.select(indexdb);
            res = jedis.hmget(key, fields);
        } catch (Exception e) {

            e.printStackTrace();
        } finally {
            returnResource(jedisPool, jedis);
        }
        return res;
    }

 

3 删除

redisUtil.hmdel(RedisCommenKey.UMENG_USER_ONLINE_REDIS, 13, value);

 

工具

//删除
    public Long hmdel(String key, int indexdb,String fields) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            jedis.select(indexdb);
            return jedis.hdel(key, fields);
        } catch (Exception e) {
            e.printStackTrace();
            return 0L;
        } finally {
            returnResource(jedisPool, jedis);
        }
    }

 

其实

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!