当前位置: 首页 > news >正文

Redis实战—附近商铺、用户签到、UV统计

  本博客为个人学习笔记,学习网站与详细见:黑马程序员Redis入门到实战 P88 - P95

目录

附近商铺

数据导入 

功能实现

用户签到

签到功能

连续签到统计 

UV统计


附近商铺

利用Redis中的GEO数据结构实现附近商铺功能,常见命令如下图所示。 

key值由特定前缀与商户类型id组成,每个GEO存储一个店铺id与该店铺的经纬度信息,如下图所示。


数据导入 

编写单元测试,将MySql数据库中的所有商铺位置信息导入Redis中,代码如下。

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

功能实现

由于SpringDataRedis的2.3.9版本并不支持Redis 6.2提供的GEOSEARCH命令,因此我们需要修改版本,代码如下。

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId><exclusions><exclusion><artifactId>spring-data-redis</artifactId><groupId>org.springframework.data</groupId></exclusion><exclusion><artifactId>lettuce-core</artifactId><groupId>io.lettuce</groupId></exclusion></exclusions>
</dependency>
<dependency><groupId>org.springframework.data</groupId><artifactId>spring-data-redis</artifactId><version>2.6.2</version>
</dependency>
<dependency><groupId>io.lettuce</groupId><artifactId>lettuce-core</artifactId><version>6.1.6.RELEASE</version>
</dependency>

Controller层代码如下。

@GetMapping("/of/type")
public Result queryShopByType(@RequestParam("typeId") Integer typeId,@RequestParam(value = "current", defaultValue = "1") Integer current,@RequestParam(value = "x", required = false) Double x,@RequestParam(value = "y", required = false) Double y
) {return shopService.queryShopByType(typeId, current, x, y);
}

接口方法的具体实现代码如下。

@Override
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,distanceString key = "shop:geo:" + typeId;GeoResults<RedisGeoCommands.GeoLocation<String>> results = stringRedisTemplate.opsForGeo().search(key,GeoReference.fromCoordinate(x, y),new Distance(5000),RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs().includeDistance().limit(end));// 4.解析出idif (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的部分ArrayList<Object> ids = new ArrayList<>(list.size());Map<String, Distance> distanceMap = new HashMap<>(list.size());list.stream().skip(from).forEach(result -> {// 4.2 获取店铺idString shopIdStr = result.getContent().getName();ids.add(Long.valueOf(shopIdStr));// 4.2 获取距离Distance distance = result.getDistance();distanceMap.put(shopIdStr, distance);});// 5.根据id查询ShopString 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);
}

用户签到

签到功能


Controller层代码如下。 

@PostMapping("/sign")
public Result sign() {return userService.sign();
}

接口方法的具体实现代码如下。

@Override
public Result sign() {// 1.获取当前登录用户信息Long userId = UserHolder.getUser().getId();// 2.获取当前日期LocalDateTime now = LocalDateTime.now();// 3.拼接keyString keySuffix = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));String key = "sign:" + userId + keySuffix;// 4.计算今天是本月的第几天int dayOfMonth = now.getDayOfMonth();// 5.写入Redis SETBIT key offset// true:写入1// false:写入0stringRedisTemplate.opsForValue().setBit(key, dayOfMonth - 1, true);return Result.ok();
}

连续签到统计 


Controller层代码如下。

@GetMapping("/sign/count")
public Result signCount() {return userService.signCount();
}

接口方法的具体实现代码如下。

@Override
public Result signCount() {// 1.获取当前登录用户信息Long userId = UserHolder.getUser().getId();// 2.获取当前日期LocalDateTime now = LocalDateTime.now();// 3.拼接keyString keySuffix = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));String key = "sign:" + userId + keySuffix;// 4.计算今天是本月的第几天int dayOfMonth = now.getDayOfMonth();// 5.获取本月截止今天为止的所有签到记录,返回结果是一个十进制数字 BITFIELD sign:5:202203 GET u14 0List<Long> result = stringRedisTemplate.opsForValue().bitField(key,BitFieldSubCommands.create() //创建子命令.get(BitFieldSubCommands.BitFieldType.unsigned(dayOfMonth)).valueAt(0)//选择子命令);if (result == null || result.isEmpty())return Result.ok(0);// 获取本月签到位图Long num = result.get(0);if (num == null || num == 0)return Result.ok(0);// 6.循环遍历int cnt = 0;//记录连续签到天数while (true) {if ((num & 1) == 0)break;num >>= 1;cnt++;}return Result.ok(cnt);
}

UV统计


测试
我们直接利用单元测试,向HyperLogLog中添加100万条数据,看看统计效果如何,测试代码如下。

@Test
void testHyperLogLog() {// 准备数组,装用户数据String[] users = new String[1000];// 数组角标int index = 0;for (int i = 1; i <= 1000000; i++) {// 赋值users[index++] = "user_" + i;// 每1000条发送一次if (i % 1000 == 0) {index = 0;stringRedisTemplate.opsForHyperLogLog().add("hll1", users);}}// 统计数量Long size = stringRedisTemplate.opsForHyperLogLog().size("hll1");System.out.println("size =" + size);
}

测试结果如下图所示。

误差 = 1 - (997593 / 1000000)≈ 0.002 可忽略不计

http://www.lryc.cn/news/401598.html

相关文章:

  • 小程序里面使用vant ui中的vant-field组件,如何使得输入框自动获取焦点
  • Html_Css问答集(12)
  • 【C语言】条件运算符详解 - 《 A ? B : C 》
  • 乘积量化pq:将高维向量压缩 97%
  • 解决一下git clone失败的问题
  • 【 香橙派 AIpro评测】烧系统运行部署LLMS大模型跑开源yolov5物体检测并体验Jupyter Lab AI 应用样例(新手入门)
  • Azure Repos 仓库管理
  • Day71 代码随想录打卡|回溯算法篇---全排列
  • 开源科学工程技术软件
  • 甄选范文“论软件维护方法及其应用”软考高级论文,系统架构设计师论文
  • 【服务器】端口映射
  • HTC 10 刷系统 LineageOS 19.1 Android 12
  • 访问者模式(Visitor Pattern)
  • mac如何查看cpu和显卡温度
  • MongoDB教程(六):mongoDB复制副本集
  • 牛客小白月赛98 (个人题解)(补全)
  • Ubuntu压缩解压各类型文件
  • 昇思学习打卡-20-生成式/GAN图像生成
  • javafx、node js、socket、OpenGL多线程
  • 【学习笔记】无人机(UAV)在3GPP系统中的增强支持(七)-通过无人机实现无线接入的独立部署
  • 模糊综合评价
  • 系统测试-白盒测试学习
  • UI设计工具选择指南:Sketch、XD、Figma、即时设计
  • Pycharm 导入 conda 环境
  • Vue封装Tooltip(提示工具)
  • Go 1.19.4 函数-Day 08
  • Docker-Nvidia(NVIDIA Container Toolkit)
  • Mongodb 3.6 数据恢复操作
  • C++ | Leetcode C++题解之第238题除自身以外数组的乘积
  • 挂耳式蓝牙耳机什么牌子好?这五款综合表现遥遥领先