ZBLOG

nestjs redis 完整用法

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

下面是 Nestjs Redis 的完整用法:

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

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

  1. import { Module } from '@nestjs/common';
  2. import { RedisModule } from '@nestjs-modules/redis';
  3. @Module({
  4. imports: [
  5. RedisModule.forRoot({
  6. // Redis 配置参数
  7. config: {
  8. host: 'localhost',
  9. port: 6379,
  10. },
  11. }),
  12. ],
  13. })
  14. export class AppModule {}
  1. 注入客户端

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

  1. import { Injectable } from '@nestjs/common';
  2. import { RedisService } from '@nestjs-modules/redis';
  3. @Injectable()
  4. export class MyService {
  5. constructor(private readonly redisService: RedisService) {}
  6. async setValue(key: string, value: string) {
  7. const client = this.redisService.getClient();
  8. await client.set(key, value);
  9. }
  10. async getValue(key: string): Promise<string> {
  11. const client = this.redisService.getClient();
  12. return client.get(key);
  13. }
  14. }
  1. 使用其他 Redis 功能

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

  1. import { Injectable } from '@nestjs/common';
  2. import { RedisService } from '@nestjs-modules/redis';
  3. @Injectable()
  4. export class MyService {
  5. constructor(private readonly redisService: RedisService) {}
  6. async usePipeline() {
  7. const client = this.redisService.getClient();
  8. const pipeline = client.pipeline();
  9. pipeline.set('key1', 'value1');
  10. pipeline.set('key2', 'value2');
  11. return pipeline.exec();
  12. }
  13. async useLuaScript() {
  14. const client = this.redisService.getClient();
  15. const script = `
  16. local value = redis.call('GET', KEYS[1])
  17. if (not value) then
  18. redis.call('SET', KEYS[1], ARGV[1])
  19. return ARGV[1]
  20. else
  21. return value
  22. end
  23. `;
  24. const result = await client.eval(script, 1, 'key', 'newValue');
  25. console.log(result); // "newValue"
  26. }
  27. }
  1. 发布/订阅

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

  1. import { Module } from '@nestjs/common';
  2. import { RedisModule } from '@nestjs-modules/redis';
  3. @Module({
  4. imports: [
  5. RedisModule.forRoot({
  6. // Redis 配置参数
  7. config: {
  8. host: 'localhost',
  9. port: 6379,
  10. },
  11. }),
  12. ],
  13. })
  14. export class AppModule {}

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

  1. import { Injectable } from '@nestjs/common';
  2. import { RedisService } from '@nestjs-modules/redis';
  3. @Injectable()
  4. export class MyService {
  5. constructor(private readonly redisService: RedisService) {}
  6. async publishMessage(channel: string, message: string) {
  7. const client = this.redisService.getClient();
  8. return client.publish(channel, message);
  9. }
  10. async subscribeToChannel(channel: string) {
  11. const client = this.redisService.getClient();
  12. return new Promise<string>((resolve, reject) => {
  13. client.subscribe(channel, (err, count) => {
  14. if (err) {
  15. reject(err);
  16. }
  17. });
  18. client.on('message', (ch, message) => {
  19. resolve(message);
  20. });
  21. });
  22. }
  23. }

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

  1. import { Controller, Get } from '@nestjs/common';
  2. import { MyService } from './my.service';
  3. @Controller()
  4. export class MyController {
  5. constructor(private readonly myService: MyService) {}
  6. @Get('/publish')
  7. async publishMessage(): Promise<string> {
  8. await this.myService.publishMessage('my-channel', 'Hello, world!');
  9. return 'Message published!';
  10. }
  11. @Get('/subscribe')
  12. async subscribeToChannel(): Promise<string> {
  13. const message = await this.myService.subscribeToChannel('my-channel');
  14. return `Received message: ${message}`;
  15. }
  16. }

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

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

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

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

联系我们

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

微信号:3007537140

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

关注我们
x

注册

已经有帐号?