Nestjs集成redis

一、安装

yarn add redis

 二、使用

1.在module中注册

import { createClient } from 'redis'

@Module({
    providers:[{
      provide: 'REDIS_CLIENT',// 定义一个服务提供者
      // 创建 Redis 客户端实例
      async useFactory() {
        const client = createClient({
          socket: {
            host: '127.0.0.1',
            port: 6379,
          }
        })
        await client.connect()
        return client;
      }
    }]
})

2.在 service中使用

import { Injectable, Inject } from '@nestjs/common';
import { RedisClientType } from 'redis';

@Injectable()
export class AppService {
  @Inject('REDIS_CLIENT')
  private redisClient: RedisClientType;

  async getHello() {
    // 获取所有值
    const value = await this.redisClient.keys('*');

    // 设置值
    const setvalue = await this.redisClient.set('demo', '11111');

    // 获取值
    const getvalue = await this.redisClient.get('demo');

    // 删除值 1代表成功 0代表没有
    const delvalue = await this.redisClient.del('demo');

    // 定时设置值 10s
    const setTimevalue = await this.redisClient.set('demo', '11111', { EX: 10 })
    return 'Hello World!';
  }
}

相关推荐

  1. Nestjs集成redis

    2023-12-28 14:56:03       28 阅读
  2. nestjs使用redis

    2023-12-28 14:56:03       49 阅读
  3. Spring boot 集成redis

    2023-12-28 14:56:03       29 阅读
  4. SpringBoot集成Redis

    2023-12-28 14:56:03       12 阅读

最近更新

  1. 探索 Neo4j:图数据库的强大应用

    2023-12-28 14:56:03       0 阅读
  2. Llama-factory源码详细解读

    2023-12-28 14:56:03       1 阅读
  3. springBoot整合mongodb

    2023-12-28 14:56:03       0 阅读
  4. STM32 系统时钟初始化函数和延时函数

    2023-12-28 14:56:03       0 阅读

热门阅读

  1. 向ES索引里面添加一个字段并更新旧文档数据

    2023-12-28 14:56:03       52 阅读
  2. Rust code: demo of message system

    2023-12-28 14:56:03       35 阅读
  3. 文件&IO

    文件&IO

    2023-12-28 14:56:03      37 阅读
  4. Flutter 官方状态管理 Provider基本使用

    2023-12-28 14:56:03       41 阅读
  5. 我的创作纪念日:感恩、感谢、感激!

    2023-12-28 14:56:03       44 阅读
  6. centos 安装 vsCode

    2023-12-28 14:56:03       36 阅读
  7. 激活函数:神经网络的生命之花

    2023-12-28 14:56:03       34 阅读
  8. 力扣:135. 分发糖果(贪心)

    2023-12-28 14:56:03       37 阅读
  9. Microsoft Edge 浏览器可能遇到的问题,和解决方法

    2023-12-28 14:56:03       50 阅读
  10. ansible 加密

    2023-12-28 14:56:03       39 阅读
  11. CentOS 8 安装指定版本ansible

    2023-12-28 14:56:03       37 阅读