目录
在前面的课程中,我们用 Redis 解决了登录认证、缓存和秒杀问题。今天,我们继续深挖 Redis 的五种数据结构在真实业务中的应用:
用 Set / ZSet 做点赞与排行榜
用 Set 做共同关注,用 ZSet 做 Feed 流收件箱
用 GEO 做附近商户
用 BitMap 做用户签到
用 HyperLogLog 做 UV 统计
每一种数据结构都不是"为了用而用",而是业务需求决定了数据结构的选择。看完这篇,你会对"什么场景用什么结构"有更清晰的认识。
一、达人探店:图文发布与点赞
1.1 发布探店笔记

探店笔记类似大众点评的评价,包含标题、文字、图片。涉及两张表:
-
tb_blog:笔记表 -
tb_blog_comments:评论表
发布流程:上传图片 → 填写内容 → 提交笔记。
1.1.1 文件上传接口
UploadController 中的uploadImage方法实现上传文件
@Slf4j
@RestController
@RequestMapping("upload")
public class UploadController {
@PostMapping("blog")
public Result uploadImage(@RequestParam("file") MultipartFile image) {
try {
// 获取原始文件名称
String originalFilename = image.getOriginalFilename();
// 生成新文件名
String fileName = createNewFileName(originalFilename);
// 保存文件
image.transferTo(new File(SystemConstants.IMAGE_UPLOAD_DIR, fileName));
// 返回结果
log.debug("文件上传成功,{}", fileName);
return Result.ok(fileName);
} catch (IOException e) {
throw new RuntimeException("文件上传失败", e);
}
}
}
SystemConstants.IMAGE_UPLOAD_DIR为图片的本地存储 路径,这里我们指定图片上传到前端服务器上,以便前端直接能够调用。路径改为:本地前端防止位置的:hm_dp\nginx-1.18.0\html\hmdp\imgs目录下
public static final String IMAGE_UPLOAD_DIR = "D:\\Code\\Java\\Object\\hm_dp\\nginx-1.18.0\\html\\hmdp\\imgs\\";
文件名用 UUID 生成,并按 hash 值分目录存储,避免单目录文件过多。
图片文件名生成方法:用于图片上传
private String createNewFileName(String originalFilename) { // 获取后缀 String suffix = StrUtil.subAfter(originalFilename, ".", true); // 生成目录 String name = UUID.randomUUID().toString(); int hash = name.hashCode(); int d1 = hash & 0xF; int d2 = (hash >> 4) & 0xF; // 判断目录是否存在 File dir = new File(SystemConstants.IMAGE_UPLOAD_DIR, StrUtil.format("/blogs/{}/{}", d1, d2)); if (!dir.exists()) { dir.mkdirs(); } // 生成文件名 return StrUtil.format("/blogs/{}/{}/{}.{}", d1, d2, name, suffix); }
1.1.2 保存笔记
直接在Controller层实现保存笔记功能,需要将当前用户信息存入Blog对象中
@PostMapping
public Result saveBlog(@RequestBody Blog blog) {
// 获取登录用户
UserDTO user = UserHolder.getUser();
blog.setUserId(user.getId());
// 保存探店博文
blogService.save(blog);
// 返回id
return Result.ok(blog.getId());
}
1.1.3 查看笔记详情

Controller层:
接收前端的blogID,调用Service层的查询方法
@GetMapping("/{id}")
public Result QueryBlogBuId(@PathVariable("id") Long id) {
return blogService.queryBlogById(id);
}
Service层:
根据BlogID查询对应的Blog信息,并根据用户id查询必要的用户信息封装到Blog中返回
@Override
public Result queryBlogById(Long id) {
// 1. 根据id查询Blog信息
Blog blog = getById(id);
// 2. 获取Blog对应的用户信息
queryBlogUser(blog);
// 返回blog信息
return Result.ok(blog);
}
private void queryBlogUser(Blog blog) {
Long userId = blog.getUserId();
User user = userService.getById(userId);
blog.setName(user.getNickName());
blog.setIcon(user.getIcon());
}
1.2 点赞功能

1.2.1 初始问题
最朴素的实现是直接
liked = liked + 1,问题很明显:一个用户可以无限点赞。@PutMapping("/like/{id}") public Result likeBlog(@PathVariable("id") Long id) { // 修改点赞数量 blogService.update() .setSql("liked = liked + 1").eq("id", id).update(); return Result.ok(); }
1.2.2 用 Set 实现"一人一赞"
思路:用 Redis 的 Set 记录点赞用户,Set 天然去重。
给Blog类添加isLike字段
在Blog类中添加下面的字段即可,@TableFiled表示是否为数据库字段
/**
* 是否点赞过了
*/
@TableField(exist = false)
private Boolean isLike;
修改点赞功能
Controller层:
@PutMapping("/like/{id}")
public Result likeBlog(@PathVariable("id") Long id) {
return blogService.likeBlogById(id);
}
Service层:
根据在Redis中查询的结果来判断当前用户是否点赞,然后进行点赞和取消点赞操作。
@Override
public Result likeBlogById(Long id) {
// 1. 获取当前用户
Long userId = UserHolder.getUser().getId();
// 2. 判断当前用户是否已经点赞
String key = RedisConstants.BLOG_LIKED_KEY + id;
Boolean isMember = stringRedisTemplate.opsForSet().isMember(key, userId.toString());
// 3. 如果未点赞,进行点赞操作
if (BooleanUtil.isFalse(isMember)) {
// 3.1 数据库点赞数+1
boolean success = update().setSql("liked = liked + 1").eq("id", id).update();
if (success) {// 点赞成功
// 3.2 保存用户id到Redis中,表示用户已经点赞
stringRedisTemplate.opsForSet().add(key, userId.toString());
}else {
log.error("点赞失败");
}
}else {
// 4. 如果已点赞,取消点赞
// 4.1 数据库点赞数-1
boolean success = update().setSql("liked = liked - 1").eq("id", id).update();
if (success) {
// 4.2 从Redis中移除用户id,表示用户取消点赞
stringRedisTemplate.opsForSet().remove(key, userId.toString());
}else {
log.error("取消点赞失败");
}
}
return Result.ok();
}
增加isLike字段赋值操作,根据笔记id为isLike字段赋值
private void isBlogLiked(Blog blog) {
// 判断当前用户是否登录,未登录不需要查询是否点赞
UserDTO user = UserHolder.getUser();
if (user == null) {
return;
}
// 1. 获取当前用户
Long userId = UserHolder.getUser().getId();
// 2. 判断当前用户是否已经点赞
String key = RedisConstants.BLOG_LIKED_KEY + blog.getId();
Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
blog.setIsLike(BooleanUtil.isTrue(score !=null));
}
该功能有一个缺陷:如果Redis中的数据被删除,但数据库中的点赞数不变,还是能够同一个用户多次点赞。
1.2.3 用 ZSet 实现“点赞排行榜”

需求:展示最早点赞的 Top5 用户。
Set 是无序的,无法排序。ZSet(SortedSet) 每个元素带一个分数(score),可以按分数排序。我们把点赞时间戳作为 score,就能拿到最早点赞的用户。
@Override
@Transactional
public Result likeBlogById(Long id) {
// 1. 获取当前用户
Long userId = UserHolder.getUser().getId();
// 2. 判断当前用户是否已经点赞
String key = RedisConstants.BLOG_LIKED_KEY + id;
Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
// 3. 如果未点赞,进行点赞操作
if (score == null) {
// 3.1 数据库点赞数+1
boolean success = update().setSql("liked = liked + 1").eq("id", id).update();
if (success) {// 点赞成功
// 3.2 保存用户id到Redis中,表示用户已经点赞,保存时间戳作为分数
stringRedisTemplate.opsForZSet().add(key, userId.toString(), System.currentTimeMillis());
}else {
log.error("点赞失败");
}
}else {
// 4. 如果已点赞,取消点赞
// 4.1 数据库点赞数-1
boolean success = update().setSql("liked = liked - 1").eq("id", id).update();
if (success) {
// 4.2 从Redis中移除用户id,表示用户取消点赞
stringRedisTemplate.opsForZSet().remove(key, userId.toString());
}else {
log.error("取消点赞失败");
}
}
return Result.ok();
}
isBlogLiked方法做相应的修改。
private void isBlogLiked(Blog blog) {
// 1. 获取当前用户
Long userId = UserHolder.getUser().getId();
// 2. 判断当前用户是否已经点赞
String key = RedisConstants.BLOG_LIKED_KEY + blog.getId();
Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
blog.setIsLike(BooleanUtil.isTrue(score ==null));
}
1.2.4 查询点赞 Top5
Controller层:
获取前端传入的笔记id,然后执行对应的方法
@GetMapping("/likes/{id}")
public Result queryBlogLikesById(@PathVariable("id") Long id) {
return blogService.queryBlogLikesById(id);
}
Service层:
根据key查询前5个点赞用户id,查询不到则直接返回,查询到了需要将id解析为Long型的列表
通过将id组合成字符串用于SQl查询
@Override
public Result queryBlogLikesById(Long id) {
String key = RedisConstants.BLOG_LIKED_KEY + id;
//1. 查询top5的点赞用户信息
Set<String> top5 = stringRedisTemplate.opsForZSet().range(key, 0, 4);
if (top5 == null || top5.isEmpty()) {
// 没人点赞
return Result.ok();
}
// 2. 解析出其中的用户id
List<Long> ids = top5.stream().map(Long::valueOf).collect(Collectors.toList());
// 3. 将用户ids列表连接成字符串,用于后面SQL语句
String idStr = StrUtil.join(",", ids);
// 4. 根据id列表查询用户信息,并将User封装为UserDTO返回
List<UserDTO> userDTOS = userService.query()
.in("id", ids)// 根据id查询用户信息
.last("ORDER BY FIELD (id," + idStr + ")")// 根据id列表进行排序,保证得到结果跟传入的id顺序一致
.list()
.stream()
.map(user -> BeanUtil.copyProperties(user, UserDTO.class))// 转换User为UserDTO
.collect(Collectors.toList());
return Result.ok(userDTOS);
}
关键点:
in("id", ids)查询结果默认按主键排序,不是按我们传入的 ids 顺序。必须用ORDER BY FIELD(id, ...)保持顺序。
二、好友关注与 Feed 流
2.1 关注 / 取关

表结构:tb_follow(user_id, follow_user_id)
Controller层:
接收前端传入的用户id和关注或取关操作,调用Service层的方法进行相应的操作
/**
* 根据用户id关注或取关用户
* @param followUserId
* @param isFollow
* @return
*/
@PutMapping("/{id}/{isFollow}")
public Result followById(@PathVariable("id") Long followUserId, @PathVariable("isFollow") Boolean isFollow) {
return followService.followById(followUserId, isFollow);
}
Service层:
这里提前判断一下用户未登录的情况,防止出现空指针异常,然后根据isFollow的值进行相应的关注和取关操作。
/**
* 根据用户id关注或取关用户
* @param followUserId
* @param isFollow
* @return
*/
@Override
public Result followById(Long followUserId, Boolean isFollow) {
// 防止未登录,出现空指针异常
UserDTO user = UserHolder.getUser();
if (user == null) {
return Result.ok();
}
// 1. 查询当前登录用户
Long userId = UserHolder.getUser().getId();
// 2. 根据操作为取关还是关注进行相应的操作
if (isFollow) {
// 2.1 关注操作,往follow表中新增数据
Follow follow = new Follow();
follow.setUserId(userId);
follow.setFollowUserId(followUserId);
save(follow);
}else {
// 2.2 取关操作,删除follow表中的数据
remove(new QueryWrapper<Follow>()
.eq("user_id", userId)
.eq("follow_user_id", followUserId));
}
return Result.ok();
}
判断是否关注:
Controller层:
/**
* 根据id判断是否关注
* @param followUserId
* @return
*/
@GetMapping("/or/not/{id}")
public Result isFollow(@PathVariable("id") Long followUserId) {
return followService.isFollow(followUserId);
}
Service层:
同样进行未登录判定,然后查询当前对应的信息
/**
* 根据id查询关注状态
* @param followUserId
* @return
*/
@Override
public Result isFollow(Long followUserId) {
// 防止未登录,出现空指针异常
UserDTO user = UserHolder.getUser();
if (user == null) {
return Result.ok();
}
// 1. 查询当前登录用户
Long userId = UserHolder.getUser().getId();
// 2. 查询是否关注
Integer count = query().eq("user_id", userId).eq("follow_user_id", followUserId).count();
// 3. 返回结果
return Result.ok(count > 0);
}
点击查询用户信息
Controller层:
/**
* 根据id查询用户信息
* @param userId
* @return
*/
@GetMapping("/{id}")
public Result queryUserById(@PathVariable("id") Long userId) {
return userService.queryUserById(userId);
}
Service层:
/**
* 根据id查询用户信息
* @param userId
* @return
*/
@Override
public Result queryUserById(Long userId) {
// 1. 查询用户信息
User user = getById(userId);
if (user == null) {
// 没有用户,直接返回
return Result.ok();
}
UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
return Result.ok(userDTO);
}
查询用户笔记功能
Controller层:
@RequestParam接收URL传参,调用Service层方法
/**
* 分页查询用户的博客
* @param current
* @param id
* @return
*/
@GetMapping("of/user")
public Result queryBlogByUserId(
@RequestParam(value = "current", defaultValue = "1") Integer current,
@RequestParam("id") Long id) {
return blogService.queryBlogByUserId(current, id);
}
Service层:
分页查询用户笔记信息并封装返回
/**
* 查询用户的博客信息
* @param current
* @param id
* @return
*/
@Override
public Result queryBlogByUserId(Integer current, Long id) {
// 根据用户查询博客信息
Page<Blog> page = query().eq("user_id", id).page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
// 获取当前页数据
List<Blog> records = page.getRecords();
return Result.ok(records);
}
功能测试
成功通过用户头像进入用户信息详情。

2.2 共同关注:Set 的交集


需求:在博主主页展示"我和博主共同关注的人"。
思路:Set 支持 SINTER(交集),把两个人的关注列表各存一个 Set,求交集即可。
Controller层:
接受前端传入的用户id,调用Service方法
/**
* 根据id查询共同关注用户
* @param id
* @return
*/
@GetMapping("/common/{id}")
public Result followCommons(@PathVariable("id") Long id) {
return followService.followCommons(id);
}
Service层:
使用Redis的set查询共同关注好友id,然后查询对应的信息封装返回
/**
* 根据id查询共同关注用户
* @param id
* @return
*/
@Override
public Result followCommons(Long id) {
if (UserHolder.getUser() == null){// 防止未登录空指针异常
return Result.ok(Collections.emptyList());
}
// 1. 查询当前登录用户
Long userId = UserHolder.getUser().getId();
// 2. 查询共同关注
String key1 = RedisConstants.USER_FOLLOWS_KEY + userId;
String key2 = RedisConstants.USER_FOLLOWS_KEY + id;
// 2.1 获取两个集合的交集
Set<String> intersect = stringRedisTemplate.opsForSet().intersect(key1, key2);
if (intersect == null || intersect.isEmpty()) {
// 没有共同关注
return Result.ok(Collections.emptyList());
}
// 2.2 将Set集合转为List集合,即用户id集合
List<Long> ids = intersect.stream().map(Long::valueOf).collect(Collectors.toList());
// 3. 查询用户信息
List<UserDTO> userDTOS = userService.listByIds(ids)
.stream()
.map(user -> BeanUtil.copyProperties(user, UserDTO.class))
.collect(Collectors.toList());
return Result.ok(userDTOS);
}
数据结构选择:Set 无序去重,天然适合"关注列表"和"交集运算"。
功能测试:

2.3 Feed 流:关注推送

需求:我关注的人发了笔记,要推送给我(类似朋友圈)。
2.3.1 三种 Feed 流模式
| 模式 | 思路 | 优点 | 缺点 |
|---|---|---|---|
| 拉模式(读扩散) | 用户读时去所有关注者发件箱拉取![]() | 节省空间 | 读取慢,大 V 粉丝多压力大 |
| 推模式(写扩散) | 发布时直接写入所有粉丝收件箱![]() | 读取快 | 大 V 发一条要写很多份,内存压力大 |
| 推拉结合 | 普通人用推,大 V 用拉+活跃粉丝推![]() | 折中 | 实现复杂 |
本项目采用推模式。
2.3.2 推送笔记到粉丝收件箱

用 ZSet 存收件箱:key = feed:userId,value = blogId,score = 时间戳。
修改新增探店笔记业务
Controller层:
/**
* 新建Blog笔记
* @param blog
* @return
*/
@PostMapping
public Result saveBlog(@RequestBody Blog blog) {
// 返回id
return blogService.saveBlog(blog);
}
Service层:
在新增笔记完成后,将笔记ID发送给所有笔记发布用户的粉丝
这里的时间戳,教程是在发送每个粉丝收件箱是给定,我觉得应该保证每个笔记在粉丝那发送时间一直,因此使用的同一个时间戳。
/**
* 新增探店笔记
* @param blog
* @return
*/
@Override
public Result saveBlog(Blog blog) {
// 1.获取登录用户
UserDTO user = UserHolder.getUser();
blog.setUserId(user.getId());
// 2.保存探店博文
boolean isSuccess = save(blog);
// 根据新增成功与否进行下一步
if (!isSuccess) {
// 3. 失败,返回错误信息
return Result.fail("新增笔记失败");
}
// 记录当前时间戳
long currentTimeMillis = System.currentTimeMillis();
// 新增成功,推送笔记id给所有粉丝
// 4.查询当前用户粉丝
List<Follow> follows = followService.query().eq("follow_user_id", user.getId()).list();
if (follows == null || follows.isEmpty()) {
// 没有粉丝,直接返回
return Result.ok(blog.getId());
}
// 5. 推送笔记id给所有的粉丝
for (Follow follow : follows) {
// 5.1 获取粉丝id
Long userId = follow.getUserId();
// 5.2 推送
String key = RedisConstants.FEED_KEY + userId;
// 这里我认为同一个blog在不同收件箱中的时间戳是否应该为同一个,表示发布时间一致
stringRedisTemplate.opsForZSet().add(key, blog.getId().toString(), currentTimeMillis);
}
// 返回id
return Result.ok(blog.getId());
}
测试:成功在新增笔记时发送笔记id到粉丝收件箱中
2.3.3 滚动分页查询收件箱

为什么不能用传统分页?
Feed 流数据不断新增。假设第 1 页拿到
10~6,此时来了新数据11,再查第 2 页(page=2),原本的5~1会变成6~2,数据重复。
解决方案:滚动分页
-
记录上一次查询的最小时间戳
lastId -
记录与该时间戳相同的元素个数
offset -
下次查询:
score <= lastId,跳过offset个
Controller层:
获取前端传入的开始时间戳和偏移量,偏移量不传时默认为0
/**
* 分页查询关注用户笔记
* @param max
* @param offset
* @return
*/
@GetMapping("/of/follow")
public Result queryBlogOfFollow(
@RequestParam("lastId") Long max, @RequestParam(value = "offset", defaultValue = "0") Integer offset){
return blogService.queryBlogOfFollow(max,offset);
}
Service层:
使用Zset的reverseRangeByScoreWithScores查询收件箱中的信息
通过解析查询的数据,得到blogId,minTine(时间戳),offset,然后查询对应的Blog信息,最后进行数据封装并返回。
/**
* 分页查询用户的关注者的博客信息
* @param max
* @param offset
* @return
*/
@Override
public Result queryBlogOfFollow(Long max, Integer offset) {
if (UserHolder.getUser() == null) return Result.fail("请先登录");
// 1.获取当前用户
Long userId = UserHolder.getUser().getId();
// 2. 查询用户的收件箱中的信息
String key = RedisConstants.FEED_KEY + userId;
Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate
.opsForZSet().reverseRangeByScoreWithScores(key, 0, max, offset, 2);
// 3. 非空判断
if (typedTuples == null || typedTuples.isEmpty()) {
return Result.ok();
}
// 4. 解析查询的数据,得到blogId,minTine(时间戳),offset
List<Long> ids = new ArrayList<>(typedTuples.size());// 设置大小,避免扩容影响系统性能
long minTine = 0; // 记录本次最小时间戳
int os = 1; // 记录最小时间戳数据个数,即下一次的偏移量
for (ZSetOperations.TypedTuple<String> typedTuple : typedTuples) {
// 4.1 获取blog的id
ids.add(Long.valueOf(typedTuple.getValue()));
// 4.2 获取分数
long time = typedTuple.getScore().longValue();
// 记录最小分数和个数
if (minTine == time) {
os++;
}else {// 更新最小分数
minTine = time;
os = 1;
}
}
// 5. 根据blog的id查询详细的信息
String idStr = StrUtil.join(",", ids);
List<Blog> blogs = query().in("id", ids).last("ORDER BY FIELD(id," + idStr + ")").list();
for (Blog blog : blogs) {
// 5.1 查询blog的用户心胸
queryBlogUser(blog);
// 5.2 查询blog的是否被点赞
isBlogLiked(blog);
}
// 6. 封装数据并返回
ScrollResult r = new ScrollResult();
r.setList(blogs);
r.setOffset(os);
r.setMinTime(minTine);
return Result.ok(r);
}
滚动分页的核心:每次查询后返回
minTime和offset,前端下次请求带回来。这样即使中间插入新数据,也不会重复或遗漏。
三、附近商户:GEO 地理坐标
3.1 GEO 是什么?
GEO 是 Redis 3.2 引入的地理坐标数据结构,常用于"附近的人""附近的店"。
常用命令:
| 命令 | 作用 |
|---|---|
GEOADD key lng lat member | 添加坐标 |
GEODIST key m1 m2 | 计算两点距离 |
GEOSEARCH key FROMLONLAT lng lat BYRADIUS r unit | 搜索范围内成员(6.2 新命令) |
GEOPOS key member | 获取成员坐标 |
3.2 导入店铺数据
思路:按 typeId 分组,每组一个 GEO key,member 存 shopId,坐标存经纬度。
/**
* 将店铺经纬度信息上传到Redis中
*/
@Test
void loadShopData(){
// 1. 查询店铺信息
List<Shop> list = shopService.list();
// 2. 对店铺信息按照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();
//3.2 获取同类型店铺集合
List<Shop> value = entry.getValue();
String key = RedisConstants.SHOP_GEO_KEY + typeId;
List<RedisGeoCommands.GeoLocation<String>> locations = new ArrayList<>(value.size());
// 3.3 把店铺信息转换为RedisGeoCommands.GeoLocation对象集合
for (Shop shop : value) {
locations.add(new RedisGeoCommands.GeoLocation<>(
shop.getId().toString(),
new Point(shop.getX(), shop.getY())
));
}
// 3.4 将当前类型shop集合写入Redis中,每种类型只写入一次
stringRedisTemplate.opsForGeo().add(key, locations);
// // 3.3 写入Redis
// for (Shop shop : value) {
// // 传统的每次写入一个shop信息,对系统负担大
// stringRedisTemplate.opsForGeo()
// .add(key, new Point(shop.getX(), shop.getY()), shop.getId().toString());
// }
}
}
批量写入比逐个
add快很多,减少网络往返。
3.3 附近商户查询

Controller层:
添加接收经纬度的参数,但不是必须的
/**
* 根据商铺类型分页查询商铺信息
* @param typeId 商铺类型
* @param current 页码
* @param x 经度 不可不要
* @param y 纬度 不可不要
* @return 商铺列表
*/
@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);
}
Service层:
根据经纬度是否传入,来判断是否需要根据位置查询,未传入则直接在数据库中分页查询即可
这里注意,由于geo的search功能是在Redis6.x之后才有的,所以本功能实现需要对Redis进行升级操作才能完成。
/**
* 根据店铺类型和经纬度分页查询店铺信息
* @param typeId
* @param current
* @param x
* @param y
* @return
*/
@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、distance
String key = RedisConstants.SHOP_GEO_KEY + typeId;
GeoResults<RedisGeoCommands.GeoLocation<String>> results = stringRedisTemplate.opsForGeo()
.search(key, GeoReference.fromCoordinate(x, y),// 根据经纬度查询
new Distance(5000),// 半径范围,以米为单位,可以传入单位
RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs()
.includeDistance().limit(end));// 这里limit是分页查询从0到end,后续需要自己调整
// 判空
if (results == null) {
return Result.ok(Collections.emptyList());
}
// 4. 解析店铺id
List<GeoResult<RedisGeoCommands.GeoLocation<String>>> list = results.getContent();
if(list.size() <= from) {
// 没有下一页了,结束
return Result.ok(Collections.emptyList());
}
// 4.1 截取form到end的数据
List<Long> ids = new ArrayList<>(list.size());
Map<String, Distance> distanceMap = new HashMap<>(list.size());
list.stream().skip(from).forEach(result -> {// skip会跳过form之前的数据
// 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());
}
return Result.ok(shops);
}
功能测试:
成功根据位置查询得到附近商铺。

版本问题:Spring Data Redis 2.3.9 不支持
GEOSEARCH,需要升级到 2.6.2 + Lettuce 6.1.6。<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>
四、用户签到:BitMap 位图
4.1 为什么用 BitMap?

如果用 MySQL 存签到,1000 万用户 × 一年 10 次 = 1 亿条记录,存储压力巨大。
BitMap 思路:一个月最多 31 天,用 31 个 bit 表示。1 表示已签到,0 表示未签到。一个月只需 4 字节!
Redis 的 String 类型底层就是 bit 数组,最大 512MB = 2³² 个 bit。

4.2 签到实现
Controller层:
/**
* 用户当日签到功能
* @return
*/
@PostMapping("/sign")
public Result sign(){
return userService.sign();
}
Service层:
这里增加对用户未登录的判断和重复签到的判定。
/**
* 用户当日签到功能
* @return
*/
@Override
public Result sign() {
// 1. 查询当前登录用户
if (UserHolder.getUser() == null){// 防止未登录
return Result.fail("请先登录");
}
Long userId = UserHolder.getUser().getId();
// 2. 获取日期
LocalDateTime now = LocalDateTime.now();
// 3. 拼接key
String keySuffix = now.format(DateTimeFormatter.ofPattern("yyyyMM"));// 某年某月
String key = RedisConstants.USER_SIGN_KEY + userId + keySuffix;
// 4. 获取今天是本月第几天
int day = now.getDayOfMonth();
// 5. 判断今天是否已经签到
Boolean isSign = stringRedisTemplate.opsForValue().getBit(key, day - 1);
if (isSign) {
// 已签到
return Result.fail("请勿重复签到");
}
// 6. 未签到,写入Redis
stringRedisTemplate.opsForValue().setBit(key, day-1, true);
return Result.ok();
}
4.3 连续签到统计
思路:

-
用
BITFIELD key GET u[day] 0取出本月到今天的二进制数据(十进制返回) -
用
num & 1判断最低位,是 1 则计数 +1 -
num >>>= 1右移,继续判断下一位
Controller层:
/**
* 连续签到次数统计
* @return
*/
@GetMapping("/sign/count")
public Result signCount(){
return userService.signCount();
}
Service层:
按照正常的逻辑来说,当天如果签到了,我们需要算到连续签到,如果当天还没有签到,但前一天签到了,应该从前一天开始统计连续签到次数,而不是当前没有签到就断签。
/**
* 连续签到次数统计
* @return
*/
@Override
public Result signCount() {
// 1. 查询当前登录用户
if (UserHolder.getUser() == null){// 防止未登录
return Result.fail("请先登录");
}
Long userId = UserHolder.getUser().getId();
// 2. 获取日期
LocalDateTime now = LocalDateTime.now();
// 3. 拼接key
String keySuffix = now.format(DateTimeFormatter.ofPattern("yyyyMM"));// 某年某月
String key = RedisConstants.USER_SIGN_KEY + userId + keySuffix;
// 4. 获取今天是本月第几天
int day = now.getDayOfMonth();
// 5. 判断今天是否已经签到
Boolean isSign = stringRedisTemplate.opsForValue().getBit(key, day - 1);
// 6.获取本月截止到今天为止的所有签到记录,返回的是一个十进制得到数字
List<Long> results = stringRedisTemplate.opsForValue().bitField(
key, BitFieldSubCommands.create().get(BitFieldSubCommands.BitFieldType.unsigned(day)).valueAt(0)
);
if (results == null || results.isEmpty()) {
return Result.ok(0);
}
// 获取签到的次数
Long num = results.get(0);
if (num == null || num == 0) {
return Result.ok(0);
}
// 7. 循环遍历,获取连续签到次数
int count = 0;
if (!isSign) {
// 如果今天未签到,不应该考虑今天,右移一位从前一天开始统计
num >>>= 1;
}
while (true) {
// 7.1 让num与1做与运算,得到数字的最后一个bit位
if ((num & 1) == 0) {
// 不是1,说明未签到,结束
break;
}else {
// 不为0,说明签到,计数器加一
count++;
}
// 7.2 将数字右移一位,相当于num/2,抛弃最后一个bit位,继续下一个bit位
num >>>= 1;
}
return Result.ok(count);
}
位运算小技巧:
n & 1取最低位,n >>> 1右移丢弃最低位。循环直到遇到 0 即可。
五、UV 统计:HyperLogLog
5.1 UV 与 PV
| 指标 | 含义 |
|---|---|
| UV(Unique Visitor) | 独立访客:同一用户一天内多次访问只算 1 次 |
| PV(Page View) | 页面浏览量:每访问一次算 1 次 |
UV 统计的难点:要去重,需要记录所有访问过的用户 ID。如果用户量大,存储成本恐怖。
5.2 HyperLogLog 原理
HLL 是一种概率算法,用极小的内存(永远 < 16KB)估算超大集合的基数。
-
优点:内存占用极低
-
缺点:有约 0.81% 的误差,且无法获取具体元素
对于 UV 这种"只看数量、不要明细"的场景,误差完全可以接受。
5.3 百万数据测试
@Test
void testHyperLogLog(){
// 准备数组,装测试数据
String[] values = new String[1000];
// 数组下标
int index = 0;
for (int i = 0; i < 1000000; i++) {
// 赋值
values[index++] = "user_" + i;
if (i % 1000 == 0) {// 每一千条发送一次
index = 0;
stringRedisTemplate.opsForHyperLogLog().add("hl1", values);
}
}
// 统计数据
Long size = stringRedisTemplate.opsForHyperLogLog().size("hl1");
System.out.println("size=" + size);
}
测试结果:

-
100 万数据,统计结果约 99 万+,误差 < 0.81%
-
内存占用仅增加 十几 KB
5.4 HLL 常用命令
| 命令 | 说明 |
|---|---|
PFADD key element... | 添加元素 |
PFCOUNT key... | 统计基数 |
PFMERGE dest source... | 合并多个 HLL |
六、总结
| 业务场景 | 推荐结构 | 原因 |
|---|---|---|
| 点赞(一人一赞) | Set | 去重 |
| 点赞排行榜 | ZSet | 需要按时间排序 |
| 关注列表 | Set | 去重 |
| 共同关注 | Set | 交集运算 |
| Feed 流收件箱 | ZSet | 按时间排序 + 范围查询 |
| 附近商户 | GEO | 地理坐标检索 |
| 用户签到 | BitMap | 极省内存 |
| UV 统计 | HyperLogLog | 超低内存估算基数 |



294




被折叠的 条评论
为什么被折叠?



