本篇介绍Reids特殊类型GEO、BitMap、HyperLog及其使用,分别对应附近商铺、用户签到、UV统计。

一、附近商铺

1、GEO数据结构

GEO就是geolocation的简写,代表地理坐标。底层是zset
在这里插入图片描述
常见命令:

命令说明
GEOADD添加一个地理空间信息,包含:经度、维度、值
GEODIST计算指定的两个点之间的距离并返回
GEOHASH将指定member的坐标转为hash字符串形式并返回
GEOPOS返回指定member的坐标
GEORADIUS指定圆心、半径,找到该园内包含的所有member,并按照与圆心之间的距离排序后返回。6.2后废弃
GEOSEARCH在指定范围内搜索member,并按照与指定点之间的距离排序后返回。6.2后新增
GEOSEARCHSTORE与GEOSEARCH 功能一致,不过可以把结果存储到一个指定的key。6.2后新增

2、附近商户搜索

(1)加载商铺数据

void loadShopData() {
        // 1.查询店铺信息
        List<Shop> list = shopService.list();
        // 2.把店铺分组,按照typeId分组,typeId一致的放到一个集合
        Map<Long, List<Shop>> map = list.stream()
        			.collect(Collectors.groupingBy(Shop::getTypeId));
        // 3.分批完成写入Redis
        for (Map.Entry<Long, List<Shop>> entry : map.entrySet()) {
            // 3.1.获取类型id
            Long typeId = entry.getKey();
            String key = SHOP_GEO_KEY + typeId;
            // 3.2.获取同类型的店铺的集合
            List<Shop> value = entry.getValue();
            List<RedisGeoCommands.GeoLocation<String>> locations = new ArrayList<>(value.size());
            // 3.3.写入redis GEOADD key 经度 纬度 member
            for (Shop shop : value) {
                // stringRedisTemplate.opsForGeo().add(key, 
                //          new Point(shop.getX(), shop.getY()), shop.getId().toString());
                locations.add(new RedisGeoCommands.GeoLocation<>(
                        shop.getId().toString(), new Point(shop.getX(), shop.getY())
                ));
            }
            stringRedisTemplate.opsForGeo().add(key, locations);
        }
    }

(2)查询店铺

public Result queryShopByType(Integer typeId, Integer current, Double x, Double y) {
        // 1.判断是否需要根据坐标查询
        if (x == null || y == null) {
            // 不需要坐标查询,按数据库查询
            Page<Shop> page = query()
                    .eq("type_id", typeId)
                    .page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
            // 返回数据
            return Result.ok(page.getRecords());
        }

        // 2.计算分页参数
        int from = (current - 1) * SystemConstants.DEFAULT_PAGE_SIZE;
        int end = current * SystemConstants.DEFAULT_PAGE_SIZE;

        // 3.查询redis、按照距离排序、分页。结果:shopId、distance
        String key = SHOP_GEO_KEY + typeId;
        // GEOSEARCH key BYLONLAT x y BYRADIUS 10 WITHDISTANCE
        GeoResults<RedisGeoCommands.GeoLocation<String>> results = stringRedisTemplate.opsForGeo().search(
                     key, 
                     GeoReference.fromCoordinate(x, y), //圆心
                     new Distance(5000),  //半径
                     RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs().includeDistance().limit(end)
                );
        // 4.解析出id
        if (results == null) {
            return Result.ok(Collections.emptyList());
        }
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> list = results.getContent();
        if (list.size() <= from) {
            // 没有下一页了,结束
            return Result.ok(Collections.emptyList());
        }
        // 4.1.截取 from ~ end的部分
        List<Long> ids = new ArrayList<>(list.size());
        Map<String, Distance> distanceMap = new HashMap<>(list.size());
        list.stream().skip(from).forEach(result -> {
            // 4.2.获取店铺id
            String shopIdStr = result.getContent().getName();
            ids.add(Long.valueOf(shopIdStr));
            // 4.3.获取距离
            Distance distance = result.getDistance();
            distanceMap.put(shopIdStr, distance);
        });
        // 5.根据id查询Shop
        String idStr = StrUtil.join(",", ids);
        List<Shop> shops = query().in("id", ids).last("ORDER BY FIELD(id," + idStr + ")").list();
        for (Shop shop : shops) {
            shop.setDistance(distanceMap.get(shop.getId().toString()).getValue());
        }
        // 6.返回
        return Result.ok(shops);
    }

二、用户签到

1、BitMap用法

底层是String类型。
我们按月来统计用户签到信息,签到记录为1,未签订则记录为0。
把每一个bit位对应每月的一天,形成映射关系。用0和1标识业务状态,这种思路称为位图(BitMap)。
Redis中利用string类型数据结构实现BitMap,因此最大上限是512M.
在这里插入图片描述

BitMap的操作命令:

命令说明
SETBIT向指定位置(offset)存入一个0或1
GETBIT获取指定位置(offset)的bit值
BITCOUNT统计BitMap中值为1的bit位的数量
BITFIELD操作(新增、修改、查询)BitMap中bit数组中的指定位置(offset)的值
BITOP将多个BitMap的结果做位运算(与、或、异或)
BITPOS查找bit数组中指定范围内第一个0或1出现的位置

2、签到功能

    public Result sign(){
        //1.获取当前用户
        Long userId = UserHolder.getUser().getId();
        //2.获取当前时间
        LocalDateTime now = LocalDateTime.now();
        //3.拼接key   用户+日期
        String suffix = now.format(DateTimeFormatter.ofPattern("yyyyMM"));
        String key = USER_SIGN_KEY + userId + ":" + suffix;
        //4.获取今天是本月第几天
        int dayOfMonth = now.getDayOfMonth();
        //5.写入redis
        stringRedisTemplate.opsForValue().setBit(key, dayOfMonth-1, true);
        return Result.ok();
    }

3、签到统计

在这里插入图片描述

    public Result signCount(){
        //1.获取当前用户
        Long userId = UserHolder.getUser().getId();
        //2.获取当前时间
        LocalDateTime now = LocalDateTime.now();
        //3.拼接key
        String suffix = now.format(DateTimeFormatter.ofPattern("yyyyMM"));
        String key = USER_SIGN_KEY + userId + ":" + suffix;
        //4.获取今天是本月第几天
        int dayOfMonth = now.getDayOfMonth();
        //5.获取本月所有的签到记录
        List<Long> result = stringRedisTemplate.opsForValue().bitField(key,
                BitFieldSubCommands.create()
                   .get(BitFieldSubCommands.BitFieldType.unsigned(dayOfMonth)).valueAt(0));
        if (null == result || result.isEmpty()) {
            return Result.ok(0);
        }
        Long num = result.get(0);
        if (null == num || num == 0) {
            return Result.ok(0);
        }
        //6.循环遍历
        int count = 0;
        while (true) {
            //6.1. 数字与1做与运算,得到数字的最后一个bit位,判断这个bit
            if ( (num & 1) == 0) {
                //如果为0, 说明未签到,结束
                break;
            } else {
                //如果为1,说明已签到,计数器+1
                count++;
            }
            //把数字右移一位,抛弃最后一个bit位,继续
            num >>>= 1;
        }
        return Result.ok(count);
    }

三、UV统计

1、HyperLogLog用法

(1)概念

  • UV 独立访客量

全称Unique Visitor,也叫独立访客量,是指通过互联网访问、浏览这个网页的自然人。1天内同一个用户多次访问该网站,只记录1次。

  • PV 页面访问量或点击量

全称Page View,也叫页面访问量或点击量,用户每访问网站的一个页面,记录一次PV,用户多次打开页面,则记录多次。往往用来衡量网站的流量。

(2)HyperLogLog用法

HyperLogLog(HLL)是从Loglog算法派生的概率算法,用于确定非常大的集合的基数,而不需要存储其所有值。
Redis中的HLL是基于String结构实现的。单个HLL的内存用小小于16kb。
在这里插入图片描述

2、实现UV统计

在这里插入图片描述

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐