代码仓库:https://github.com/changeclass/koa2-weibo

广场页与个人页面相似度很高,唯一不同的就是广场页的数据需要进行缓存。

  1. 控制器层

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    /**
    * @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 }

  2. 缓存层

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    /**
    * @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
    }