使用Egg.js和Redis实现视频热度增长功能
使用Egg.js和Redis实现视频热度增长功能
在本篇博客中,我们将学习如何使用Egg.js和Redis来实现视频热度增长功能。通过封装Redis服务并在控制器中调用该服务,我们能够实时记录视频热度的增长,并提供一个简单易用的API接口来增加视频评论时更新热度数据。
步骤一:封装Redis服务
首先,我们需要封装一个Redis服务,用于管理和操作Redis数据。在service
目录下新建redis.js
文件,配置Redis连接并处理连接事件。
const Redis = require('ioredis');
const redis = new Redis(6379, '127.0.0.1');
redis.on('error', err => {
if (err) {
console.log('Redis 链接错误');
redis.quit();
}
});
redis.on('ready', () => {
console.log('redis链接成功');
});
module.exports.redis = redis;
步骤二:增加视频热度的服务
接下来,我们在service
目录下新建redisHot.js
文件,定义增加视频热度的服务。
const { redis } = require('./redis');
const Service = require('egg').Service;
class RedisHotService extends Service {
async hotInc(videoId, incNum) {
let data = await redis.zscore('videoHots', videoId);
if (data) {
await redis.zincrby('videoHots', incNum, videoId);
} else {
await redis.zadd('videoHots', incNum, videoId);
}
}
}
module.exports = RedisHotService;
步骤三:在控制器中使用Redis服务
在controller
目录下的video.js
文件中,增加视频评论的同时调用Redis服务来增加视频热度。
const Controller = require('egg').Controller;
class VideoController extends Controller {
async createComment() {
const body = this.ctx.request.body;
const videoId = this.ctx.params.videoId;
this.ctx.validate({
content: { type: 'string' }
}, body);
const { Video, VideoComment } = this.app.model;
const video = await Video.findById(videoId);
if (!video) {
this.ctx.throw(404, '视频不存在');
}
const comment = await new VideoComment({
content: body.content,
user: this.ctx.user._id,
video: videoId
}).save();
if (comment) {
video.commentCount = await VideoComment.countDocuments({
video: videoId
});
await video.save();
// 增加热度
this.service.redisHot.hotInc(videoId, 2);
this.ctx.body = {
msg: "评论成功"
};
} else {
this.ctx.throw(501, '视频评论失败');
}
}
}
module.exports = VideoController;
步骤四:验证功能是否成功
我们可以通过Redis命令行工具和Postman来验证热度增长功能是否成功。
- 记录下初始热度排行:
// 进入redis
redis-cli
// 查看当前的热度排行
zrevrange videoHots 0 -1 withscores
- 使用Postman添加评论
- 次查看热度排行,验证热度是否增加。
3.png
总结
通过本次教程,我们学习了如何在Egg.js中集成Redis,实现视频热度增长功能。具体包括封装Redis服务、创建增加热度的服务、在控制器中调用服务并通过Postman验证接口。这样,我们能够有效地管理和记录视频热度,提升用户互动体验。
转载自:https://juejin.cn/post/7379121513419161637