点赞排行榜
基于redis的sortedSet实现的点赞功能,可以做到每个人只能对一个作品点一次赞。并可以基于时间戳进行点赞的先后排序。
以下是代码实现
- 点赞功能
@Override
public Result likeBlog(Long id) {
//1. 获取登录用户
Long userId = UserHolder.getUser().getId();
//2. 判断当前用户是否已经点赞
String key = BLOG_LIKED_KEY + id;
Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
if(score == null){
//3. 如果未点赞,可以点赞
//3.1 数据库点赞数 +1
boolean isSuccess = update().setSql("liked = liked + 1").eq("id", id).update();
//3.2 保存到redis集合
if(isSuccess){
stringRedisTemplate.opsForZSet().add(key, userId.toString(), System.currentTimeMillis());
}
}else{
//4. 如果已点赞,取消点赞
//4.1 数据库点赞数 -1
boolean isSuccess = update().setSql("liked = liked - 1").eq("id", id).update();
//4.2 redis集合删除用户
if(isSuccess){
stringRedisTemplate.opsForZSet().remove(key, userId.toString());
}
}
return Result.ok();
}
- 统计前五个点赞的用户
@Override
public Result queryBlogLikes(Long id) {
String key = BLOG_LIKED_KEY + id;
//1. 查询top5的用户
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 idsStr = StrUtil.join(",", ids);
//3. 根据id查询用户
List<User> userDTOs = userService.query()
.in("id",ids)
//这一步很重要!!!!!!!!!
.last("ORDER BY FIELD(id," + idsStr + ")").list()
.stream()
.map(user -> BeanUtil.copyProperties(user, User.class))
.collect(Collectors.toList());
//4.返回
return Result.ok(userDTOs);
}
这里要注意的是,当获取用户id,从数据库获取用户具体数据时,用到的是 id in (k1,k2,k3) 。mysql默认的语法会忽略k1 k2 k3 的排序,而是自动基于序号进行排序,应该用ORDER BY FIELD指定排序,才能保证top5的顺序准确性。
共同关注
在进行关注操作时,可以通过redis中的set来进行统计,一方面可以保证每个用户只能关注另一个用户一次,另一方面可以方便统计不同用户关注列表之间的交集,也就是俗称的共同关注
- 关注代码
@Override
public Result follow(Long followUserId, Boolean isFollow) {
//获取当前用户id
Long userId = UserHolder.getUser().getId();
//1. 判断是关注还是取关
if(isFollow){
//2. 关注,新增数据
Follow follow = new Follow();
follow.setUserId(userId);
follow.setFollowUserId(followUserId);
boolean isSuccess = save(follow);
if(isSuccess){
String key = "follows:" + userId;
stringRedisTemplate.opsForSet().add(key,followUserId.toString());
}
}else{
//3. 取关,删除
boolean isSuccess = remove(new QueryWrapper<Follow>()
.eq("user_id", userId)
.eq("follow_user_id", followUserId));
if(isSuccess){
String key = "follows:" + userId;
stringRedisTemplate.opsForSet().remove(key,followUserId.toString());
}
}
return Result.ok();
}
- 判断是否关注
@Override
public Result isfollow(Long followUserId) {
Long userId = UserHolder.getUser().getId();
Integer count = query().eq("user_id", userId).eq("follow_user_id", followUserId).count();
if(count>0){
return Result.ok(true);
}else{
return Result.ok(false);
}
}
- 共同关注
@Override
public Result followCommons(Long id) {
//获取当前用户
Long userId = UserHolder.getUser().getId();
String key1 = "follows:" + userId;
String key2 = "follows:" + id;
//求交集
Set<String> intersect = stringRedisTemplate.opsForSet().intersect(key1, key2);
if(intersect == null || intersect.isEmpty()){
return Result.ok(Collections.emptyList());
}
List<Long> ids = intersect.stream().map(Long::valueOf).collect(Collectors.toList());
List<UserDTO> users = userService.listByIds(ids)
.stream()
.map(user -> BeanUtil.copyProperties(user, UserDTO.class))
.collect(Collectors.toList());
return Result.ok(users);
}
}
最后一步用的stream流式编程,我觉得很巧妙
签到统计
利用redis的BITSET进行签到统计,计算出当前是当月的多少钱,再设置对应的位数,即可完成签到功能,在统计连续签到时,只需要从后向前遍历直到遇到0为止
- 签到功能
@Override
public Result sign() {
//获取当前登录的用户
Long userId = UserHolder.getUser().getId();
//获取日期
LocalDateTime now = LocalDateTime.now();
//拼接key
String keySuffix = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
String key = USER_SIGN_KEY + userId + keySuffix;
//获取天数
int dayOfMonth = now.getDayOfMonth();
//写入redis
stringRedisTemplate.opsForValue().setBit(key, dayOfMonth - 1, true);
return Result.ok();
}
- 签到统计
@Override
public Result signCount() {
//获取当前登录的用户
Long userId = UserHolder.getUser().getId();
//获取日期
LocalDateTime now = LocalDateTime.now();
//拼接key
String keySuffix = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
String key = USER_SIGN_KEY + userId + keySuffix;
//获取天数
int dayOfMonth = now.getDayOfMonth();
//获取本月截止今天为止所有的签到记录,返回的是一个十进制数字
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 == 0 || num == null){
return Result.ok(0);
}
//循环遍历
int count = 0;
while(true){
if ((num & 1) == 0) {
//如果为0,连续签到断了
break;
}else{
//与1做与运算,得到数字中1的个数
count++;
}
//右移
num >>>= 1;
}
return Result.ok(count);
}
UV统计
统计独立访问量,用redis的hll来统计100w次访问,只需要消耗不超过16kb的内存,很夸张。
@Test
void testHyperLogLog() {
String[] values = new String[1000];
int j = 0;
for (int i = 0; i < 1000000; i++) {
j = i % 1000;
values[j] = "user_" + i;
if(j == 999){
stringRedisTemplate.opsForHyperLogLog().add("hl2", values);
}
}
//统计数量
Long count = stringRedisTemplate.opsForHyperLogLog().size("hl2");
System.out.println("count = " + count);
}
最终消耗了14kb
Feed流
feed流是向用户推送信息的信息流,分为推模式,拉模式,和推拉结合模式,依次简述为
- 推模式:用户发送博客后推送到每一个粉丝的收件箱
- 拉模式:用户发送博客后储存到发件箱,用户看的时候拉取发件箱的内容
- 推拉结合:对于活跃粉丝采用推模式保证信息的时效,对于普通粉丝采用拉模式减少成本消耗。
这篇blog只说基于redis的sortedset实现的推模式。
- 保存博客的同时向所有粉丝推送
@Override
public Result saveBlog(Blog blog) {
// 获取登录用户
UserDTO user = UserHolder.getUser();
blog.setUserId(user.getId());
// 保存探店博文
boolean isSuccess = save(blog);
if(isSuccess){
//查询笔记作者的所有粉丝
List<Follow> follows = followService.query().eq("follow_id", user.getId()).list();
//推送笔记id给所有粉丝
for (Follow follow : follows) {
Long followUserId = follow.getUserId();
String key = FEED_KEY + followUserId;
stringRedisTemplate.opsForZSet().add(key, blog.getId().toString(), System.currentTimeMillis());
}
}
// 返回id
return Result.ok(blog.getId());
}
- 用户登录查询收件箱
//1.获取当前用户
Long userId = UserHolder.getUser().getId();
String key = FEED_KEY + userId;
//2.查询收件箱
Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet()
.reverseRangeByScoreWithScores(key, 0, max, offset, 2);
if(typedTuples == null || typedTuples.isEmpty()){
return Result.ok();
}
滚动分页查询
滚动分页查询是为了防止在获取页面时,数据刷新导致下标更新,从而在第二页出现了相同的数据。
这里可以利用redis中的zset,根据上一次查询的最小值定义下一次的最大值,并判断最小值出现了几次,定义下一次的偏移量(offset)
List<Long> ids = new ArrayList<>(typedTuples.size());
long minTime = 0;
int os = 1;
for (ZSetOperations.TypedTuple<String> tuple : typedTuples) {
ids.add(Long.valueOf(tuple.getValue()));
long temp = tuple.getScore().longValue();
if(temp == minTime){
os++;
}else{
minTime = temp;
os = 1;
}
}
//4.根据id拿到blog
String idsStr = StrUtil.join(",", ids);
List<Blog> blogs = query()
.in("id",ids)
.last("ORDER BY FIELD(id," + idsStr + ")").list();
for (Blog blog : blogs) {
//查询Blog有关的对象
queryBlogUser(blog);
//查询blog是否被点赞
isBlogLiked(blog);
}
附近店铺
在新版redis中更新了GEO数据类型,可以存储经纬度,并计算出直线距离,基于这点可以实现对附近商铺进行距离远近的排序。
@Override
public Result queryShopByType(Integer typeId, Integer current, Double x, Double y) {
// 判断是否需要根据坐标查询
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());
}
// 计算分页参数
int from = (current - 1) * SystemConstants.DEFAULT_PAGE_SIZE;
int end = current * SystemConstants.DEFAULT_PAGE_SIZE;
// 根据坐标查询redis,按照距离排序、分页查询。结果:shopId,maxDistance
String geoKey = SHOP_GEO_KEY + typeId;
// GEOSEARCH key BYLONLAT x y BYRADIUS 10 WITHDISTANCE WITHHASH
GeoResults<RedisGeoCommands.GeoLocation<String>> results = stringRedisTemplate.opsForGeo().search(
geoKey,
GeoReference.fromCoordinate(x, y), // 查询以给定的经纬度为中心的圆形区域
new Distance(10000), // 查询10km范围内的店铺,单位默认为米
RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs().includeDistance().limit(end) // 分页查询0~end条
);
// 解析出id
if (results == null) {
// 未查到结果,返回错误
return Result.fail("没有查到店铺");
}
List<GeoResult<RedisGeoCommands.GeoLocation<String>>> list = results.getContent();
// from跳过前面元素不足from个,跳过后集合为空,说明查完了没有下一页了,返回空集合
if (list.size() <= from) {
return Result.ok(Collections.emptyList());
}
// 截取from ~ end的部分,方法一:list.subList(from, end); 方法二:stream流的skip方法,跳过from前面的元素,从from开始,截取end-from个元素
List<Long> ids = new ArrayList<>(list.size());
Map<String, Distance> distanceMap = new HashMap<>(list.size());
list.stream().skip(from).forEach(result -> {
// 获取店铺id(Member)
String shopIdStr = result.getContent().getName();
ids.add(Long.valueOf(shopIdStr));
// 获取距离
Distance distance = result.getDistance();
distanceMap.put(shopIdStr, distance);
});
// 根据id查询店铺数据
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);
}
以上仅代表个人拙见,如有不足请在评论区指出