八、从零模拟新浪微博-广场页面
代码仓库:https://github.com/changeclass/koa2-weibo
广场页与个人页面相似度很高,唯一不同的就是广场页的数据需要进行缓存。
控制器层
/** * @description: 微博广场 * @author: 小康 * @url: https://xiaokang.me * @Date: 2020-12-19 14:38:57 * @LastEditTime: 2020-12-19 14:38:58 * @LastEditors: 小康 */ const { getSquareCacheList } = require('../cache/blog') const { PAGE_SIZE } = require('../config/constant') const { SuccessModel } = require('../model/ResModel') /** * @author: 小康 * @url: https://xiaokang.me * @param {*} pageIndex 页面索引 * @description: 获得广场的微博列表 */ async function getSquareBlogList(pageIndex = 0) { // cache const result = await getSquareCacheList(pageIndex, PAGE_SIZE) const blogList = result.blogList return new SuccessModel({ isEmpty: blogList.length === 0, blogList, pageSize: PAGE_SIZE, pageIndex, count: result.count }) } module.exports = { getSquareBlogList }缓存层
/** * @description: 微博缓存层 * @author: 小康 * @url: https://xiaokang.me * @Date: 2020-12-19 14:53:13 * @LastEditTime: 2020-12-19 14:53:13 * @LastEditors: 小康 */ const { get, set } = require('./_redis') const { getBlogListByUser } = require('../services/blog') // redis key 前缀 const KEY_PREFIX = 'weibo:square' /** * @author: 小康 * @url: https://xiaokang.me * @param {*} pageIndex * @param {*} pageSize * @description: 获取广场列表的缓存 */ async function getSquareCacheList(pageIndex, pageSize) { const key = `${KEY_PREFIX}${pageIndex}_${pageSize}` // 尝试获取缓存 const cacheResult = await get(key) if (cacheResult != null) { return cacheResult } else { // 没有缓存则读取数据库 const result = await getBlogListByUser({ pageIndex, pageSize }) // 设置缓存 过期时间1分钟 set(key, result, 60) // 返回数据 return result } } module.exports = { getSquareCacheList }
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 小康博客!
评论
TwikooDisqusjs








