前端实战-基于Nodejs的redis使用

现在大多数的网站架构都包含着redis,主要目的是充作请求缓存的作用。但是在Nodejs中如何去很好的使用redis,可以如下操作。

安装redis包

项目主要使用的是以Express为框架的后端架构,所以先安装express-redis-cache

yarn add express-redis-cache
or
npm i express-redis-cache -S

使用express-redis-cahce

项目基于Nuxtjs,项目目录截图如下:

image.png
express-redis-cache的引入配置
const cache = require('express-redis-cache')({
    client: redisClient, //Redis实例,
    prefix: `以某个字符开头`,
    expire: 300,// 缓存时长 单位秒
  })

配置主要分为这三个部份,redis实例的创建相信不需要多说了。

如何在接口处使用创建好的cache

先上代码!

app.use(
    '/dashboard',
    (req, res, next) => {
      // res.express_redis_cache_name = `dashboard-${req.path.split('/')[1]}-${JSON.stringify(req.body)}`
      res.express_redis_cache_name = 'dashboard-' + buildHash(`${req.path.split('/')[1]}-${JSON.stringify(req.body)}`)
      next()
    },
    cache.route(),
    dashboardRouter
  )
  1. 使用中间件为每个路由设置cache name, 为了让好看点,这里使用了hash函数,代码块如下:
 (req, res, next) => {
      // res.express_redis_cache_name = `dashboard-${req.path.split('/')[1]}-${JSON.stringify(req.body)}`
      res.express_redis_cache_name = 'dashboard-' + buildHash(`${req.path.split('/')[1]}-${JSON.stringify(req.body)}`)
      next()
    },
  1. 使用cache.route(),请求的缓存主要就是使用这个方法。

结语

怎么样,很简单吧!!
更多文档请参考: https://www.npmjs.com/package/express-redis-cache

你可能感兴趣的:(前端实战-基于Nodejs的redis使用)