给大家推荐一个库,地址: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;
        }
    }
    // Pop
    async 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一样丝滑




















