菜鸟总是要踩很多坑,记录坑让其他菜鸟少踩。
一、安装依赖
npm install cache-manager --save
npm install cache-manager-redis-store --save
npm install @types/cache-manager -D
二、redis-cache.service.ts
import { Injectable, Inject, CACHE_MANAGER } from '@nestjs/common';
import { Cache } from 'cache-manager';
@Injectable()
export class RedisCacheService {
constructor(
@Inject(CACHE_MANAGER)
private cacheManager: Cache
) {
}
cacheSet(key: string, value: string, ttl: number) {
this.cacheManager.set(key, value, { ttl: ttl }, (err: any) => {
if (err) {
throw err;
}
})
}
async cacheGet(key: any): Promise<any> {
return this.cacheManager.get(key);
}
}
三、redis-cache.module.ts
import { Module, CacheModule } from '@nestjs/common';
import * as redisStore from 'cache-manager-redis-store';
import { RedisCacheService } from './redis-cache.service';
@Module({
imports: [
CacheModule.register({
store: redisStore,
host: 'localhost',
port: 6379,
auth_pass: "XXXXXX",
db: 3 // 目标库
}),
],
controllers: [],
providers: [RedisCacheService],
exports: [RedisCacheService],
})
export class RedisCacheModule { }
四、在其他module中使用redis,如usersModule
4.1 users.module.ts
import { Module } from '@nestjs/common';
import { UserService } from './users.service';
import { UserController } from './users.controller';
import { userProviders } from './users.providers';
import { RedisCacheModule } from '../redis/redis-cache.module';
@Module({
imports: [
RedisCacheModule,
],
controllers: [UserController],
providers: [...userProviders, UserService],
exports: [UserService],
})
export class UserModule { }
4.2 users.provider.ts
import { Connection } from 'typeorm';
import { User } from './entities/user.entity';
export const userProviders = [
{
provide: 'USERS_REPOSITORY',
useFactory: (connections: Connection) => connections.getRepository(User)
inject: ['DATABASE_CONNECTION'],
},
];
关于typeorm和数据库连接的内容跟本文内容无关就不写了。
4.3 users.controller.ts
import { Controller, Get } from "@nestjs/common";
import { UserService } from "./users.service";
@Controller("User")
export class UserController {
constructor(
private readonly userService: UserService,
) { }
@Get("get/:id")
findOne(@Param("id") id: string) {
return this.userService.findOne(id);
}
}
4.4 users.service.ts
import { Injectable, Inject } from '@nestjs/common';
import { Repository } from 'typeorm';
import { User } from './entities/user.entity';
import { RedisCacheService } from '../redis/redis-cache.service';
@Injectable()
export class UserService {
constructor(
@Inject("USERS_REPOSITORY")
private readonly userRepository: Repository<User>,
private readonly redisCacheService: RedisCacheService,
) { }
async findOne(id: string): Promise<any> {
const result = await this.userRepository
.createQueryBuilder("user")
.where({ id: id })
.getOne();
// 写入redis记录,ttl缓存期设置为30天
this.redisCacheService.cacheSet("userId_" + id, JSON.stringify(result), 60 * 60 * 24 * 30)
return result
}
}
4.5 redis取值操作
const cacheData = await this.redisCacheService.cacheGet("userId_" + id)
本文档详细介绍了如何在Nest.js应用中集成并使用Redis进行数据缓存,包括安装依赖、配置服务模块,以及在usersModule中的具体使用方法,旨在帮助开发者避免常见问题。
2820





