当前位置: 首页 > news >正文

ts 新版的@nestjs/commo下redis的注册使用

一.我之前在@nestjs/commo 10以下时候注册redis时候,用在最新的"@nestjs/common": "^10.0.0",上面有问题,store添加上后,一直没能够注册成功,不加上我在redis工具上又没有查看到保存的数据,说明数据没有按照规定注册保存到想要的位置。

①添加依赖,我这里添加的依赖是符合"@nestjs/common": "^10.0.0",的,在我使用的时间下,安装的是最新的版本。

npm i @nestjs-modules/ioredis ioredis

创建redisManage模块

nest generate module redisManage

之后再创建service

nest genereate service redisManage

②在redis模块中注册redis

import { Module } from '@nestjs/common';
import { RedisModule } from '@nestjs-modules/ioredis';
import { RedisManageService } from './redis-manage.service';
@Module({imports: [RedisModule.forRoot({type: 'single',url:`//${process.env.REDIS_HOST}:${process.env.REDIS_PORT}` ||'redis://localhost:6379',}),],providers: [RedisManageService],exports: [RedisManageService],
})
export class RedisManageModule {}

③在service中创建方法,可以给其他的模块方法使用

import { Injectable } from '@nestjs/common';
import Redis from 'ioredis';
import { InjectRedis } from '@nestjs-modules/ioredis';@Injectable()
export class RedisManageService {constructor(@InjectRedis() private readonly redisCache: Redis) {}async get(key: string, isObject?: boolean) {type ResultType = string | object;const result: ResultType = await this.redisCache.get(key);if (isObject) {return JSON.parse(result);}return result;}// 如果自行定义过期时间,请使用该方法,并带第三个参数async set(key: string, value: string | number | object, ttl?: number) {const strValue = JSON.stringify(value);if (typeof value === 'object') {await this.redisCache.set(key,strValue,'EX',ttl ? ttl : 60 * 60 * 24 * 7,);} else {await this.redisCache.set(key, value, 'EX', ttl ? ttl : 60 * 60 * 24 * 7);}}async reset() {await this.redisCache.reset();}async del(key: string) {await this.redisCache.del(key);}
}

说明:这里的ttl时间为秒

60*60*24*7表示一周时间

这里创建处理之后,在使用redis添加数据之后,就可以通过redis工具查看到数据


http://www.mrgr.cn/news/15299.html

相关文章:

  • 【Pyspark-驯化】一文搞懂Pyspark中表连接的使用技巧
  • Java Email发送:如何配置SMTP服务器发信?
  • 亚马逊aws的弹性与可扩展性解析
  • 选择排序【详解】
  • vue报错解决
  • Zabbix 配置win系统登录和钉钉告警
  • python如何另起一行
  • 浅谈【数据结构】栈和队列之队列
  • 5G BWP
  • PyTorch深度学习实战(26)—— PyTorch与Multi-GPU
  • 登山第一梯:使用rviz显示bag包中的点云数据
  • python设置Excel表格样式与单元格属性
  • 分布式性能测试-通篇讲解 Locust 性能测试
  • 微积分复习笔记 Calculus Volume 1 - 1.2 Basic Classes of Functions
  • 拉取/启动kafka的docker镜像
  • 高性能web服务器4——Nginx反向代理A
  • IDEA/Pycharm/Goland/jetbrains2024.2全家桶汉化失败问题解决
  • Prometheus和Grafana构建现代服务器监控体系
  • 极狐GitLab 如何管理 Kubernetes 集群?
  • Tinder 平台账户多登如何防止封禁账号?