ZBLOG

nestjs redis 完整用法

Nestjs Redis 是一个基于 Redis 的模块,可以让你在 Nest.js 应用程序中轻松地使用 Redis。它提供了丰富的功能,包括连接池、发布/订阅、管道、事务、Lua 脚本等。

下面是 Nestjs Redis 的完整用法:

  1. 安装依赖
npm install --save @nestjs-modules/redis redis
  1. 引入模块

在你的应用程序模块中引入 Redis 模块:

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

@Module({
  imports: [
    RedisModule.forRoot({
      // Redis 配置参数
      config: {
        host: 'localhost',
        port: 6379,
      },
    }),
  ],
})
export class AppModule {}
  1. 注入客户端

在你的服务中注入 Redis 客户端:

import { Injectable } from '@nestjs/common';
import { RedisService } from '@nestjs-modules/redis';

@Injectable()
export class MyService {
  constructor(private readonly redisService: RedisService) {}

  async setValue(key: string, value: string) {
    const client = this.redisService.getClient();
    await client.set(key, value);
  }

  async getValue(key: string): Promise<string> {
    const client = this.redisService.getClient();
    return client.get(key);
  }
}
  1. 使用其他 Redis 功能

除了基本的 GET 和 SET 命令之外,Nestjs Redis 还支持 Redis 的其他功能。例如,您可以使用管道和 Lua 脚本来执行复杂的 Redis 命令:

import { Injectable } from '@nestjs/common';
import { RedisService } from '@nestjs-modules/redis';

@Injectable()
export class MyService {
  constructor(private readonly redisService: RedisService) {}

  async usePipeline() {
    const client = this.redisService.getClient();
    const pipeline = client.pipeline();

    pipeline.set('key1', 'value1');
    pipeline.set('key2', 'value2');

    return pipeline.exec();
  }

  async useLuaScript() {
    const client = this.redisService.getClient();

    const script = `
      local value = redis.call('GET', KEYS[1])
      if (not value) then
        redis.call('SET', KEYS[1], ARGV[1])
        return ARGV[1]
      else
        return value
      end
    `;

    const result = await client.eval(script, 1, 'key', 'newValue');
    console.log(result); // "newValue"
  }
}
  1. 发布/订阅

您还可以使用 Nestjs Redis 来实现发布/订阅模式。首先,将 Redis 模块导入到应用程序模块中,并创建一个频道:

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

@Module({
  imports: [
    RedisModule.forRoot({
      // Redis 配置参数
      config: {
        host: 'localhost',
        port: 6379,
      },
    }),
  ],
})
export class AppModule {}

然后,在您的服务中实现发布和订阅:

import { Injectable } from '@nestjs/common';
import { RedisService } from '@nestjs-modules/redis';

@Injectable()
export class MyService {
  constructor(private readonly redisService: RedisService) {}

  async publishMessage(channel: string, message: string) {
    const client = this.redisService.getClient();
    return client.publish(channel, message);
  }

  async subscribeToChannel(channel: string) {
    const client = this.redisService.getClient();
    return new Promise<string>((resolve, reject) => {
      client.subscribe(channel, (err, count) => {
        if (err) {
          reject(err);
        }
      });

      client.on('message', (ch, message) => {
        resolve(message);
      });
    });
  }
}

最后,您可以在 Nestjs 控制器中使用这些服务:

import { Controller, Get } from '@nestjs/common';
import { MyService } from './my.service';

@Controller()
export class MyController {
  constructor(private readonly myService: MyService) {}

  @Get('/publish')
  async publishMessage(): Promise<string> {
    await this.myService.publishMessage('my-channel', 'Hello, world!');
    return 'Message published!';
  }

  @Get('/subscribe')
  async subscribeToChannel(): Promise<string> {
    const message = await this.myService.subscribeToChannel('my-channel');
    return `Received message: ${message}`;
  }
}

这就是 Nestjs Redis 的完整用法。使用 Nestjs Redis,您可以轻松地将 Redis 集成到 Nest.js 应用程序中,并利用其强大的功能来实现复杂的应用程序逻辑。

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=2326

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?