Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

【缓存】redis

  • 先在机器上安装redis6.0,并开启

  • 安装

    npm i -S redis
    
    • 最新版本 4.0.1
      • 要求redis服务要在5.0以上
  • lib/db文件夹下,新建redis_core.js文件,进行封装

    import { createClient } from 'redis';
    import config from "config";
    import { Log } from "../utils/api_log.js";
    const log = new Log("redis_core");
    
    export const redisClient = createClient(config.get("redisConfig"));
    
    redisClient.on('error', (err) =>{
        log.error('redis client err:', err);
        redisClient.quit();
    })
    
    await redisClient.connect();
    
    • 需要配置url,默认是redis://127.0.0.1:6379
    • 可选配置username,默认是default
  • 封装后在路由中使用

    import { redisClient } from "../../../db/redis_core.js";
    
    router.get("/test/redis", async ctx => {
        log.info("test redis")
        await redisClient.set('key', 'value');
        const result = await redisClient.get('key');
        ctx.body = result;
    })