点赞(set)
需求:
-
同一个用户只能点赞一次,再次点击则取消点赞
-
如果当前用户已经点赞,则点赞按钮高亮显示(前端已实现,判断字段Blog类的isLike属性)
实现:
-
给Blog类中添加一个isLike字段,标示是否被当前用户点赞
-
利用Redis的set集合判断是否点赞过,以blog为key,用户id为value,未点赞过添加用户id,已点赞过则移除用户id
-
在根据id查询和分页查询Blog的业务中,判断当前登录用户是否点赞过,赋值给isLike字段
部分代码如下:
public Result likeBlog(Long id) {
//1.获取登录用户
Long userId = UserHolder.getUser().getId();
//2.判断当前登录用户是否已经点赞
String key = "blog:liked:" + id;
Boolean isMember = stringRedisTemplate.opsForSet().isMember(key, userId.toString());
if (BooleanUtil.isFalse(isMember)){
//3.如果未点赞,可以点赞
//3.1.数据库点赞数 + 1
boolean isSuccess = update().setSql("liked = liked + 1").eq("id", id).update();
//3.2.保存用户到Redis的set集合
if (isSuccess){
stringRedisTemplate.opsForSet().add(key, userId.toString());
}
} else {
//4.如果已点赞,取消点赞
//4.1.数据库点赞数 - 1
boolean isSuccess = update().setSql("liked = liked - 1").eq("id", id).update();
//4.2.把用户从Redis的set集合移除
if (isSuccess){
stringRedisTemplate.opsForSet().remove(key, userId.toString());
}
}
return Result.ok();
}
点赞排行榜(sortedSet)
在探店笔记的详情页面,把给该笔记点赞的人显示出来,比如最早点赞的TOP5,形成点赞排行榜。
部分代码如下:
public Result queryBlogLikes(Long id) {
String key = BLOG_LIKED_KEY + id;
//1.查询top5的点赞用户 zrange key 0 4
Set<String> top5 = stringRedisTemplate.opsForZSet().range(key, 0, 4);
if (top5 == null || top5.isEmpty()){
return Result.ok(Collections.emptyList());
}
//2.解析其中的用户id
List<Long> ids = top5.stream().map(Long::valueOf).collect(Collectors.toList());
String idStr = StrUtil.join(",", ids);
//3.根据用户id查询用户 where id in(5 ,1) order by field
List<UserDTO> userDTOS = userService.query()
.in("id", ids).last("order by field(id," + idStr + ")").list()
.stream()
.map(user -> BeanUtil.copyProperties(user, UserDTO.class))
.collect(Collectors.toList());
//4.返回
return Result.ok(userDTOS);
}
需要注意两点:
-
sortedSet没有isMember,用score是否存在来判断有没有点赞。
-
mysql中,
where in(x,x,x)会自动根据id排序,需要手动order by field指定排序。
共同关注(set)
实现共同关注功能。在博主个人页面展示出当前用户与博主的共同关注,也就是交集。
部分代码如下:
public Result followCommons(Long id) {
//1.获取登录用户
Long userId = UserHolder.getUser().getId();
String key = "follows:" + userId;
//2.求交集
String key2 = "follows:" + id;
Set<String> intersect = stringRedisTemplate.opsForSet().intersect(key, key2);
if (intersect == null || intersect.isEmpty()){
//无交集
return Result.ok(Collections.emptyList());
}
//3.解析id集合
List<Long> ids = intersect.stream().map(Long::valueOf).collect(Collectors.toList());
//4.查询用户
List<UserDTO> users = userService.listByIds(ids)
.stream()
.map(user -> BeanUtil.copyProperties(user, UserDTO.class))
.collect(Collectors.toList());
return Result.ok(users);
}
内容推送(sortedSet)
Feed流
Feed流产品有两种常见模式:
Timeline:不做内容筛选,简单的按照内容发布时间排序,常用于好友或关注。例如朋友圈
-
优点:信息全面,不会有缺失。并且实现也相对简单
-
缺点:信息噪音较多,用户不一定感兴趣,内容获取效率低
智能排序:利用智能算法屏蔽掉违规的、用户不感兴趣的内容。推送用户感兴趣信息来吸引用户
-
优点:投喂用户感兴趣信息,用户粘度很高,容易沉迷
-
缺点:如果算法不精准,可能起到反作用
该项目中的个人页面,是基于关注的好友来做Feed流,因此采用Timeline的模式。该模式的实现方案有三种:
拉模式:也叫做读扩散,每个人都有自己的发件箱和收件箱。
推模式:也叫做写扩散,只有收件箱。
推拉结合模式:也叫做混写模式,兼具推和拉两种模式的优点。
3种模式对比:
该项目没有大v,采用推模式。
滚动分页查询
传统的分页在Feed流是不适用的,因为数据会不断更新。
传统分页示意图:
需要记录每次查询的最后一条,然后从这个位置开始去查询数据,不依赖于索引查询,list只能通过索引和首尾查询,因此pass;而sortedSet可以按照score范围进行排名,把score设为时间戳,每次查询记录最小的时间戳,下次查询时找比她更小的,从而实现滚动分页查询。
推送到粉丝收件箱
部分代码如下:
public Result savaBlog(Blog blog) {
//1.获取登录用户
UserDTO user = UserHolder.getUser();
blog.setUserId(user.getId());
//2.保存探店笔记
boolean isSuccess = save(blog);
if (!isSuccess){
return Result.fail("新增笔记失败");
}
//3.查询笔记作者的所有粉丝 select * from tb_follow where follow_user_id = ?
List<Follow> follows = followService.query().eq("follow_user_id", user.getId()).list();
//4.推送笔记id给所有粉丝
for (Follow follow : follows) {
//4.1获取粉丝id
Long userId = follow.getUserId();
//4.2推送
String key = "feed:" + userId;
stringRedisTemplate.opsForZSet().add(key, blog.getId().toString(), System.currentTimeMillis());
}
//5.返回id
return Result.ok(blog.getId());
}
实现滚动分页
zrevrangebyscore key max min withscores limit offset count
4个查询参数:
-
max:
-
第一次:当前时间戳
-
后续:上一次查询的最小时间戳
-
-
min:固定值,0
-
offset(偏移值):从第几个开始查
-
第一次:0
-
后续:因为有可能出现相同score,所以要取上一次查询中最小的元素的个数
-
-
count:固定值,每次查询的数量
部分代码如下:
public Result queryBlogOfFollow(Long max, Integer offset) {
//1.获取当前用户
Long userId = UserHolder.getUser().getId();
//2.查询收件箱 zrevrangebyscore key max min limit offset count
String key = "feed:" + 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、score(时间戳)、offset(偏移值)
List<Long> ids = new ArrayList<>(typedTuples.size()); //默认16,指定和typedTuples大小一致
long minTime = 0;
int os = 1; //至少有一个最小值
for (ZSetOperations.TypedTuple<String> tuple : typedTuples) {
//4.1.获取id
ids.add(Long.valueOf(tuple.getValue()));
//4.2.获取分数(时间戳)
long time = tuple.getScore().longValue();
if (time == minTime){
os++;
} else {
minTime = time;
os = 1; //此时不是最小时间,需要重置
}
}
//5.1.根据id查询blog
String idStr = StrUtil.join(",", ids);
List<Blog> blogs = query().in("id", ids).last("order by field(id," + idStr + ")").list();
for (Blog blog : blogs) {
//5.2.查询发布blog的用户
queryBlogUser(blog);
//5.3.查询blog是否被点赞
isBlogLiked(blog);
}
//6.封装并返回
ScrollResult r = new ScrollResult();
r.setList(blogs);
r.setOffset(os);
r.setMinTime(minTime);
return Result.ok(r);
}
附近商户(geo)
GEO是Geolocation的简写形式,代表地理坐标。Redis在3.2版本中加入了对GEO的支持,本质上是sortedSet。常见命令有:
- GEOADD:添加一个地理空间信息,包含:经度(longitude)、纬度(latitude)、值(member)
- GEODIST:计算指定的两个点之间的距离并返回
- GEOHASH:将指定member的坐标转为hash字符串形式并返回
- GEOPOS:返回指定member的坐标
- GEORADIUS:指定圆心、半径,找到该圆内包含的所有member,并按照与圆心之间的距离排序后返回。6.2以后已废弃
- GEOSEARCH:在指定范围内搜索member,并按照与指定点之间的距离排序后返回。范围可以是圆形或矩形。6.2.新功能
- GEOSEARCHSTORE:与GEOSEARCH功能一致,不过可以把结果存储到一个指定的key。 6.2.新功能
导入店铺数据到GEO
以typeId为key,shopId为member存入geo。
@Test
void loadShopDate() {
//1.查询店铺消息
List<Shop> list = shopService.list();
//2.把店铺按照typeId分组,id一致的放到一个集合
Map<Long, List<Shop>> map = list.stream().collect(Collectors.groupingBy(Shop::getTypeId));
//分组后map:1={shop1},2={shop2}...
//3.分组完成后写入reid
for (Map.Entry<Long, List<Shop>> entry : map.entrySet()) {
//3.1.获取类型id
Long typeId = entry.getKey();
String key = "shop:geo:" + typeId;
//3.2.获取同类型的店铺集合
List<Shop> value = entry.getValue();
List<RedisGeoCommands.GeoLocation<String>> locations = new ArrayList<>(value.size());
//3.3.写入redis groadd 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); //单个写变成批量写
}
}
实现查询附近商户
难点在于分页截取数据。
部分代码如下:
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, DEFAULT_PAGE_SIZE));
//返回数据
return Result.ok(page.getRecords());
}
//2.计算分页参数
int from = (current - 1) * DEFAULT_PAGE_SIZE;
int end = current * DEFAULT_PAGE_SIZE;
//3.根据redis按照距离排序进行分页查询。结构:shopId,distance
String key = "shop:geo:" + typeId;
GeoResults<RedisGeoCommands.GeoLocation<String>> results = stringRedisTemplate.opsForGeo() //geosearch bylonlat x y byradius 10 withistance
.search(
key,
GeoReference.fromCoordinate(x, y),
new Distance(5000),
RedisGeoCommands.GeoRadiusCommandArgs.newGeoRadiusArgs()
.includeDistance().limit(end) //默认0到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.截取form到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);
}
签到(bitMap)
把每一个bit位对应当月的每一天,形成映射关系。用0和1标示业务状态,这种思路就称为位图(BitMap)。这样就可以用极小的空间,来实现了大量数据的存储。
Redis中是用string类型数据结构实现BitMap,因此最大上限是512M,转换为bit则是 2^32个bit位。
常用命令:
- SETBIT:向指定位置(offset)存入一个0或1
- GETBIT :获取指定位置(offset)的bit值
- BITCOUNT :统计BitMap中值为1的bit位的数量
- BITFIELD :操作(查询、修改、自增)BitMap中bit数组中的指定位置(offset)的值,查询返回的是十进制数
- BITPOS :查找bit数组中指定范围内第一个0或1出现的位置
实现签到功能
部分代码如下:
public Result sign() {
//1.获取当前登录用户
Long userId = UserHolder.getUser().getId();
//2.获取日期
LocalDateTime now = LocalDateTime.now();
String keySuffix = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
//3.拼接key
String key = USER_SIGN_KEY + userId + keySuffix;
//4.获取今天是本月的第几天,从1开始
int dayOfMonth = now.getDayOfMonth();
//5.写入redis setbit key offset 1
stringRedisTemplate.opsForValue().setBit(key, dayOfMonth - 1, true);
return Result.ok();
}
统计连续签到天数
需要注意三点:
-
连续签到天数:指从最后一次签到开始向前开始统计,直到遇到第一次未签到为止,计算总的签到次数。该项目做的是统计本月到今天为止的连续签到天数。
-
得到本月到今天为止的所有签到数据:
bitfield key get count offset-
count:查多少个。
-
offset:从第几个开始查。
-
返回的是一个十进制数。
-
-
从后向前遍历每个bit位:与1做于运算得到最后一个bit位,随后右移一位,使下一个bit位成为最后一个bit位。
部分代码如下:
重点在于while循环。
public Result signCount() {
//1.获取当前登录用户
Long userId = UserHolder.getUser().getId();
//2.获取日期
LocalDateTime now = LocalDateTime.now();
String keySuffix = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
//3.拼接key
String key = USER_SIGN_KEY + userId + keySuffix;
//4.获取今天是本月的第几天
int dayOfMonth = now.getDayOfMonth();
//5.获取本月截至今天为止的所有签到记录,返回的是一个十进制的数字 bitfield sign:1:202301 get u14 0
List<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 count = 0;
while (true) {
//6.1.让这个数字于1做与运算,得到数字的最后一个bit位,判断这个bit位是否为0
if ((num & 1) == 0){
//如果为0,说明未签到,结束
break;
} else {
//如果不为0,说明已签到,计数器+1
count++;
}
//把数字右移一位,抛弃最后一位,继续下一个bit位
num >>>= 1; //无符号右移
}
return Result.ok(count);
}
统计数据(hyperLogLog)
UV和PV
-
UV:全称Unique Visitor,也叫独立访客量,是指通过互联网访问、浏览这个网页的自然人。1天内同一个用户多次访问该网站,只记录1次。
-
PV:全称Page View,也叫页面访问量或点击量,用户每访问网站的一个页面,记录1次PV,用户多次打开页面,则记录多次PV。往往用来衡量网站的流量。
通常来说UV会比PV大很多,所以衡量同一个网站的访问量,需要综合考虑很多因素,所以我们只是单纯的把这两个值作为一个参考值。
UV统计在服务端做会比较麻烦,因为要判断该用户是否已经统计过了,需要将统计过的用户信息保存。但是如果每个访问的用户都保存到Redis中,数据量会非常恐怖,那怎么处理呢?
Hyperloglog(HLL)是从Loglog算法派生的概率算法,用于确定非常大的集合的基数,而不需要存储其所有值。相关算法原理可以参考:juejin.cn/post/684490…
Redis中的HLL是基于string结构实现的,元素唯一,单个HLL的内存永远小于16kb,内存占用低的令人发指!作为代价,其测量结果是概率性的,有小于0.81%的误差。不过对于UV统计来说,这完全可以忽略。
UV统计-测试百万数据的统计
测试思路:直接利用单元测试,向HyperLogLog中添加100万条数据,看看内存占用和统计效果如何。
@Test
void testHyperLogLog() {
String[] values = new String[1000];
int j = 0;
for (int i = 0; i < 1000000; i++) {
//分1000次发送,循环次数/模的数:1000000/1000
j = i % 1000;
values[j] = "user_" + i;
if (j == 999){
//发送到Redis
stringRedisTemplate.opsForHyperLogLog().add("hl2", values);
}
}
//统计数量
Long count = stringRedisTemplate.opsForHyperLogLog().size("hl2");
System.out.println("count = " + count); //count = 997593
}
经过测试发现他的误差是在允许范围内,并且内存占用极小。