[Nestjs] 使用redis的基础配置,以及基本使用的介绍

要在 NestJS 中使用 Redis,需要安装依赖npm install --save redis fastify-redis

app.module.ts 中导入 RedisModuleCacheModule

import { Module } from '@nestjs/common';
import { RedisModule } from 'nestjs-redis';
import { CacheModule } from '@nestjs/common';

@Module({
  imports: [
    RedisModule.register({
      host: 'localhost', // Redis 服务器地址
      port: 6379, // Redis 服务器端口号
      password: 'your_password', // Redis 密码(如果需要)
    }),
    CacheModule.register(),
  ],
})
export class AppModule {}

创建一个使用 Redis 的服务示例:

import { Injectable, Inject } from '@nestjs/common';
import { Redis } from 'ioredis';
import { CACHE_MANAGER } from '@nestjs/common';

@Injectable()
export class RedisService {
  constructor(
    @Inject(CACHE_MANAGER) private cacheManager: CacheManager,
    @Inject('REDIS') private readonly redis: Redis,
  ) {}

  async setValue(key: string, value: any) {
    await this.cacheManager.set(key, value);
  }

  async getValue(key: string): Promise<any> {
    return await this.cacheManager.get(key);
  }

  async removeFromCache(key: string) {
    await this.cacheManager.del(key);
  }
}

使用 Redis 服务:

import { Controller, Get, Param } from '@nestjs/common';
import { RedisService } from './redis.service';

@Controller('example')
export class ExampleController {
  constructor(private readonly redisService: RedisService) {}

  @Get('set/:key/:value')
  async setKeyValue(
    @Param('key') key: string,
    @Param('value') value: string,
  ): Promise<void> {
    await this.redisService.setValue(key, value);
  }

  @Get('get/:key')
  async getValueByKey(@Param('key') key: string): Promise<any> {
    return await this.redisService.getValue(key);
  }

  @Get('remove/:key')
  async removeFromCache(@Param('key') key: string): Promise<void> {
    await this.redisService.removeFromCache(key);
  }
}

以上步骤中,我们使用 nestjs-redis 模块提供的 RedisModule 来连接和配置 Redis。在 RedisService 中,我们使用 CACHE_MANAGER 标记注入缓存管理器,并通过 REDIS 标记注入 Redis 实例。

ExampleController 中,我们使用 RedisService 来展示如何设置、获取和删除缓存数据。需要了解更多 Redis 操作,请参考 Redis 官方文档:https://redis.io/documentation。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值