本文主要是介绍nestJs链接redis,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
给大家推荐一个库,地址:Yarn
service
import { Injectable } from '@nestjs/common';
import { RedisService as RedisServices, DEFAULT_REDIS_NAMESPACE } from '@liaoliaots/nestjs-redis';
import Redis from 'ioredis';@Injectable()
export class RedisService {private readonly redis: Redis;constructor(private readonly redisService: RedisServices) {this.redis = this.redisService.getClient(DEFAULT_REDIS_NAMESPACE);}async set(key: string, value: string): Promise<boolean> {try {await this.redis.set(key, value);return true;} catch (error) {console.error('设置键值对出错:', error);return false;}}async get(key: string): Promise<string | null> {try {return await this.redis.get(key);} catch (error) {console.error('获取值出错:', error);return null;}}async del(key: string): Promise<boolean> {try {await this.redis.del(key);return true;} catch (error) {console.error('删除键出错:', error);return false;}}// push方法接受一个键和一个值数组作为参数async leftPushAll(key: string, values: any[]): Promise<boolean> {try {await this.redis.lpush(key, ...values);return true;} catch (error) {console.error(error);return false;}}// Popasync rightPop(key: string): Promise<any> {try {if (!key) return null;return await this.redis.rpop(key);} catch (error) {console.error(error);return null;}}// }
controller
import { Controller, Get } from '@nestjs/common';
import { ApiOperation, ApiTags } from '@nestjs/swagger';
import { RedisService } from './redis.service';@ApiTags('redis')
@Controller('redis')
export class RedisController {constructor(private readonly redisService: RedisService) { }@ApiOperation({ summary: 'Setredis测试' })@Get("/redis")setRedisInfo() {return this.redisService.set('qvfan', 'hello redis');}@ApiOperation({ summary: 'Getredis测试2' })@Get("/redis2")getRedisInfo() {return this.redisService.get('qvfan');}@ApiOperation({ summary: 'Delredis测试' })@Get("/redis3")delRedisInfo() {return this.redisService.del('qvfan');}@ApiOperation({ summary: 'lpushredis测试' })@Get("/redis4")lpushRedisInfo() {return this.redisService.leftPushAll('qvfan', ['11212144', '11212145']);}@ApiOperation({ summary: 'rpopredis测试' })@Get("/redis5")rpopRedisInfo() {return this.redisService.rightPop('qvfan');}
}
效果和java一样丝滑
这篇关于nestJs链接redis的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!