Redis实战篇
达人探店
发布探店笔记
代码实现:
@GetMapping("/{id}")
public Result queryBlogById(@PathVariable("id") Long id){
return blogService.queryBlogById(id);
}
@Override
public Result queryBlogById(Long id) {
//1.查询blog
Blog blog = getById(id);
if(blog == null){
return Result.fail("笔记不存在!");
}
//2.查询blog有关的用户
queryBlogUser(blog);
//3.查询blog是否被点赞了
isBlogLiked(blog);
return Result.ok(blog);
}
点赞
完善点赞功能
需求:
- 同一个用户只能点赞—一次,再次点击则取消点赞
- 如果当前用户已经点赞,则点赞按钮高亮显示(前端已实现,判断字段Blog类的isLike属性)
实现步骤:
- 给Blog类中添加一个isLike字段,标示是否被当前用户点赞
- 修改点赞功能,利用Redis的set集合判断是否点赞过,未点赞过则点赞数+1,已点赞过则点赞数-
- 修改根据id查询Blog的业务,判断当前登录用户是否点赞过,赋值给isLike字段
- 修改分页查询Blog业务,判断当前登录用户是否点赞过,赋值给isLike字段
/*********************步骤一*******************/
/**
* 是否点赞过了
*/
@TableField(exist = false)
private Boolean isLike;
/*********************步骤二*******************/
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的set集合 zadd key value score
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的set集合中移除
if(isSuccess){
stringRedisTemplate.opsForZSet().remove(key,userId.toString());
}
}
return Result.ok();
}
/*********************步骤三*******************/
@Override
public Result queryBlogById(Long id) {
//1.查询blog
Blog blog = getById(id);
if(blog == null){
return Result.fail("笔记不存在!");
}
//2.查询blog有关的用户
queryBlogUser(blog);
//3.查询blog是否被点赞了
isBlogLiked(blog);
return Result.ok(blog);
}
/*********************步骤四*******************/
@Override
public Result queryHotBlog(Integer current) {
// 根据用户查询
Page<Blog> page = query()
.orderByDesc("liked")
.page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
// 获取当前页数据
List<Blog> records = page.getRecords();
// 查询用户
records.forEach(blog -> {
this.queryBlogUser(blog);
this.isBlogLiked(blog);
});
return Result.ok(records);
}
/*********************调用判断是否点赞的函数*******************/
private void isBlogLiked(Blog blog) {
//1.获取登录用户
UserDTO user = UserHolder.getUser();
if(user == null){
// return Result.fail("用户未登录");
return;
}
Long userId = user.getId();
//2.判断当前用户是否已经点赞
String key = BLOG_LIKED_KEY + blog.getId();
Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
blog.setIsLike(score != null);
}
点赞排行
根据需求这里选着SortedSet数据结构
代码实现:
public Result queryBlogLikes(Long id) {
//1.查询top5的点赞用户 zrange key 0 4
String key = BLOG_LIKED_KEY+ id;
Set<String> top5 = stringRedisTemplate.opsForZSet().range(key, 0, 4);
//2.解析出期中的用户id
if(top5 == null || top5.isEmpty()){
return Result.ok(Collections.emptyList());
}
List<Long> ids = top5.stream().map(Long::valueOf).collect(Collectors.toList());
String idstr = StrUtil.join(",", ids);
//3.根据用户id查询用户
//注意: mybatis-plus自带的批量查询只会根据id的顺序返回数据,不能做到按时间排序,这里采用拼接 order by field来实现:
List<User> users = userService.query().in("id",ids).last("ORDER BY FIELD(id,"+idstr+")").list();
if(users == null || users.isEmpty()){
return Result.ok(Collections.emptyList());
}
List<UserDTO> userDTOS = users.stream().map(user ->
BeanUtil.copyProperties(user, UserDTO.class))
.collect(Collectors.toList());
//4.返回
return Result.ok(userDTOS);
}
好友关注
关注和取关
需求: 基于该表数据结构,实现两个接口:
- 关注和取关接口
- 判断是否关注的接口
- 关注是User之间的关系,是博主与粉丝的关系,数据库中有一张tb follow表来标示:
代码实现:
@Override
public Result follow(Long followUserId, Boolean isFollow) {
// 获取登录用户
Long userId = UserHolder.getUser().getId();
String key = "follows" + userId;
//1.判断是关注还是取关
if (isFollow) {
//2.关注新增数据
Follow follow = new Follow();
follow.setUserId(userId);
follow.setFollowUserId(followUserId);
boolean isSuccess = save(follow);
if (isSuccess) {
// 把关注用户的id放入redis的set集合 sadd userId followerUserId
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) {
//把关注的用户id移除
stringRedisTemplate.opsForSet().remove(key, followUserId.toString());
}
}
return Result.ok();
}
@Override
public Result isfollow(Long followUserId) {
// 获取登录用户
UserDTO user = UserHolder.getUser();
//查询是否关注
Integer count = query().eq("user_id", user.getId()).eq("follow_user_id", followUserId).count();
return Result.ok(count > 0);
}
共同关注
博主个人首页依赖两个接口:
- 根据id查询user信息:
@Override
public Result queryUser(Long userId) {
User user = userService.getById(userId);
if (user == null) {
return Result.ok();
}
UserDTO userDTO = new UserDTO();
BeanUtils.copyProperties(user, userDTO);
return Result.ok(userDTO);
}
- 根据id查询博主的探店笔记:
@Override
public Result queryBlogById(Long id) {
//1.查询blog
Blog blog = getById(id);
if (blog == null) {
return Result.fail("笔记不存在!");
}
//2.查询blog有关的用户
queryBlogUser(blog);
//3.查询blog是否被点赞了
isBlogLiked(blog);
return Result.ok(blog);
}
@Override
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());
}
//解析出id
List<Long> ids = intersect.stream().map(Long::valueOf).collect(Collectors.toList());
List<User> users = iUserService.listByIds(ids);
List<UserDTO> userDTOS = users.stream().map(user -> {
UserDTO userDTO = new UserDTO();
BeanUtils.copyProperties(user, userDTO);
return userDTO;
}).collect(Collectors.toList());
return Result.ok(userDTOS);
}
关注推送
Feed流产品有两种常见模式:
Timeline: 不做内容筛选,简单的按照内容发布时间排序,常用于好友或关注。例如朋友圈
- 优点:信息全面,不会有缺失。并且实现也相对简单
- 缺点:信息噪音较多,用户不一定感兴趣,内容获取效率低
智能排序: 利用智能算法屏蔽掉违规的、用户不感兴趣的内容。推送用户感兴趣信息来吸引用户
- 优点:投喂用户感兴趣信息,用户粘度很高,容易沉迷
- 缺点:如果算法不精准,可能起到反作用
本例中的个人页面,是基于关注的好友来做Feed流,因此采用Timeline的模式。该模式的实现方案有
- 拉模式
- 推模式
- 推拉结合
需求:
- 修改新增探店笔记的业务,在保存blog到数据库的同时,推送到粉丝的收件箱
- 收件箱满足可以根据时间戳排序,必须用Redis的数据结构实现
- 查询收件箱数据时,可以实现分页查询
@Override
public Result saveBlog(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_KEY + userId;
stringRedisTemplate.opsForZSet().add(key,blog.getId().toString(), System.currentTimeMillis());
}
// 返回id
return Result.ok(blog.getId());
}
附近商铺
GEO数据结构
GEO就是Geolocation的简写形式,代表地理坐标。Redis在3.2版本中加入了对GEO的支持,允许存储地理坐标信息,帮助我们根据经纬度来检索数据。常见的命令有:
GEOADD: 添加一个地理空间信息,包含:经度(longitude)、纬度(latitude)、值(member)GEODIST:计算指定的两个点之间的距离并返回
GEOHASH: 将指定member的坐标转为hash字符串形式并返回
GEOPOS: 返回指定member的坐标
GEORADIUS: 指定圆心、半径,找到该圆内包含的所有member,并按照与圆心之间的距离排序后返回。6.2后废弃
GEOSEARCH: 在指定范围内搜索member,并按照与指定点之间的距离排序后返回。范围可以是圆形或矩形。6.2.新功能
GEOSEARCHSTORE: 与GEOSEARCH功能一致,不过可以把结果存储到一个指定的key。6.2.新功能
附近商户搜索
@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,距离
String key = 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));
//4.解析出id 根据id查询店铺
if(results == null){
return Result.ok(Collections.emptyList());
}
List<GeoResult<RedisGeoCommands.GeoLocation<String>>> content = results.getContent();
if(content.size() <= from){
//没有下一页
return Result.ok(Collections.emptyList());
}
//截取from 到 end 的部分
List<Long> ids = new ArrayList<>(content.size());
Map<String,Distance> distanceMap = new HashMap<>(content.size());
content.stream().skip(from).forEach(result ->{
//获取id
String shopIdStr = result.getContent().getName();
ids.add(Long.valueOf(shopIdStr));
//获取距离
Distance distance = result.getDistance();
distanceMap.put(shopIdStr,distance);
});
//5.根据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);
}
用户签到
BitMap用法
Redis中是利用string类型数据结构实现BitMap,因此最大上限是512M,转换为bit则是2的32次个bit位。BitMap的操作命令有:
SETBIT: 向指定位置(offset)存入一个0或1
GETBIT︰ 获取指定位置(offset)的bit值
BITCOUNT: 统计BitMap中值为1的bit位的数量
BITFIELD: 操作(查询、修改、自增)BitMap中bit数组中的指定位置(offset)的值
BITFIELD_RO: 获取BitMap中bit数组,并以十进制形式返回
BITOP: 将多个BitMap的结果做位运算(与、或、异或)BITPOS:查找bit数组中指定范围内第一个0或1出现的位置
签到功能
@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 setbit key offset
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);
}
//循环遍历
int count = 0;
Long num = result.get(0);
if (num == null || num == 0) {
return Result.ok(0);
}
while (true) {
//让这个数字与1做与运算,得到数字的最后一个bit位
//判断bit位是否为0
if ((num & 1) == 0) {
//如果为0,说明未签到,结束
break;
} else {
//不为0 ,已签到,计数器+1;
count++;
}
//右移数字一位,抛弃最后一个bit位
//num >>>=1;
num = num >> 1;
}
return Result.ok(count);
}
UV统计
HyperLogLog用法
首先我们搞懂两个概念:
UV: 全称Unique Visitor,也叫独立访客量,是指通过互联网访问、浏览这个网页的自然人。1天内同一个用户多次访问该网站,只记录1次。
PV: 全称Page View,也叫页面访问量或点击量,用户每访问网站的一个页面,记录1次PV,用户多次打开页面,则记录多次PV。往往用来衡量网站的流量。
UV统计在服务端做会比较麻烦,因为要判断该用户是否已经统计过了,需要将统计过的用户信息保存。但是如果每个访问的用户都保存到Redis中,数据量会非常恐怖。
实现UV统计
@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) {
//发送到redis
stringRedisTemplate.opsForHyperLogLog().add("h12", values);
}
}
//统计数量
Long count = stringRedisTemplate.opsForHyperLogLog().size("h12");
System.out.println("count=" + count);
}
- HyperLogLog的作用
- 做海量数据的统计工作
- HyperLogLog的优点:
- 内存占用极低
- 性能非常好
- HyperLogLog的缺点:·
- 有一定的误差