当尝试使用 Redis 和缓存管理器在 Nest.js 中学习缓存时,Postman 会抛出 500 内部服务器错误。“缓存管理器”:“^5.1.6”,“缓存管理器-redis-store”:“^3.0.1”。链接到发送请求时终端错误的屏幕截图(https://pastenow.ru/e9d6921c47dd71093458135ada911dc1)这是我的代码
/* App.module.ts */
import { Module, CacheModule } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { TypeOrmModule } from '@nestjs/typeorm';
import { WinstonModule } from 'nest-winston';
import * as winston from 'winston';
import * as Joi from 'joi';
import type { ClientOpts } from 'redis';
import * as redisStore from 'cache-manager-redis-store';
import { AppController } from './app.controller';
import { UsersModule } from './users/users.module';
import { AppService } from './app.service';
import configuration from './configuration';
const shcema = Joi.object({
port: Joi.number().integer().default(3000),
database: Joi.object({
host: Joi.string()
.pattern(/postgres:\/\/[a-zA-Z]/)
.required(),
port: Joi.number().integer().required(),
username: Joi.string(),
password: Joi.string(),
}),
});
@Module({
imports: [
ConfigModule.forRoot({
load: [configuration],
isGlobal: true,
validationSchema: shcema,
}),
TypeOrmModule.forRootAsync({
imports: [ConfigModule],
useClass: AppService,
}),
CacheModule.register<ClientOpts>({
store: redisStore,
host: 'localhost',
port: 6379,
}),
WinstonModule.forRoot({
levels: {
critical_error: 0,
error: 1,
special_warning: 2,
another_log_level: 3,
info: 4,
},
transports: [
new winston.transports.Console({ format: winston.format.simple() }),
new winston.transports.File({ filename: 'error.log', level: 'error' }),
],
}),
UsersModule,
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
/* App.service.ts */
import { Injectable, Inject } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { TypeOrmOptionsFactory } from '@nestjs/typeorm';
import { WINSTON_MODULE_PROVIDER } from 'nest-winston';
import { Logger } from 'winston';
@Injectable()
export class AppService implements TypeOrmOptionsFactory {
constructor(
private readonly configService: ConfigService,
@Inject(WINSTON_MODULE_PROVIDER) private readonly logger: Logger,
) {}
createTypeOrmOptions() {
/* this.logger.log('Creating a user'); */
return this.configService.get('database');
}
getHello(): string {
return 'Hello Nest.Js';
}
}
/* App.controller.ts */
import { Controller, Get, CACHE_MANAGER, Inject } from '@nestjs/common';
import { Cache } from 'cache-manager';
import { AppService } from './app.service';
@Controller()
export class AppController {
constructor(
private readonly appService: AppService,
@Inject(CACHE_MANAGER) private cache: Cache,
) {}
@Get()
async getHello() {
const someValue = this.appService.getHello();
await this.cache.get(someValue);
if (someValue) {
return someValue;
}
const result = this.appService.getHello();
await this.cache.set(result, { ttl: 1000 });
return result;
}
}