在我的项目中使用nestjs框架,并使用现金管理器与redis缓存连接。我能够与redis连接,但是当我使用任何方法(如set/get )时,它会显示一个错误,而set不是函数。添加了应用程序模块、服务和包json以供参考。
app.module.ts
import { Module, CacheModule } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
const config = require('./config');
import { Logger } from './logger';
import * as redisStore from 'cache-manager-redis-store';
import type { RedisClientOptions } from "redis"
@Module({
imports: [
CacheModule.register({
// @ts-ignore
store: async () => await redisStore({
// Store-specific configuration:
socket: {
host: '******',
port: 6380,
password: '*****'
}
})
}),
HttpModule
],
controllers: [AppController],
providers: [AppService, Logger],
exports: [Logger],
})
export class AppModule {}app.service.ts
import { Cache } from 'cache-manager';
import {
HttpException,
HttpStatus,
Injectable,
OnApplicationBootstrap,
OnApplicationShutdown,
CACHE_MANAGER,
Inject
} from '@nestjs/common';
@Injectable()
export class DeviceOnboardService
implements OnApplicationBootstrap, OnApplicationShutdown
{
constructor(
@Inject(CACHE_MANAGER) private cacheManager: Cache,
private logger: Logger
) {}
async getData(){
await this.cacheManager.set('test', 'XYZ', 600);
}
}package.json
"dependencies": {
"@nestjs/common": "^8.0.0",
"@nestjs/core": "^8.0.0",
"cache-manager": "^5.1.3",
"cache-manager-redis-store": "^3.0.1",
"redis": "^4.3.1",
},
"devDependencies": {
"@nestjs/cli": "^8.0.0",
"@nestjs/schematics": "^8.0.0",
"@nestjs/testing": "^8.0.0",
"@types/cache-manager": "^4.0.2",
"@types/express": "^4.17.13",
"@types/jest": "27.5.0",
"@types/node": "^16.0.0",
"@types/supertest": "^2.0.11",
"@typescript-eslint/eslint-plugin": "^5.0.0",
"@typescript-eslint/parser": "^5.0.0",
"eslint": "^8.0.1",
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-prettier": "^4.0.0",
"jest": "28.0.3",
"prettier": "^2.3.2",
"source-map-support": "^0.5.20",
"supertest": "^6.1.3",
"ts-jest": "28.0.1",
"ts-loader": "^9.2.3",
"ts-node": "^10.0.0",
"tsconfig-paths": "4.0.0",
"typescript": "^4.3.5"
},误差
[Nest] 25598 - 22/11/2022, 19:32:15 ERROR store.set is not a function发布于 2022-12-01 08:24:28
异步配置需要使用useFactory进行配置,如果需要动态配置,它允许您使用异步等待并注入服务。
当您使用useFactory时,您可以使用导入数组和注入。如下面的示例所示,如果需要,可以在“imports”数组中导入configModule,在inject中导入configService。
CacheModule.registerAsync<RedisClientOptions>({
imports: [ConfigModule],
useFactory: async (configService: ConfigService) => {
const store = await redisStore({
socket: {
host: configService.get('REDIS_HOST'),
port: configService.get('REDIS_PORT'),
},
});
return {
store: {
create: () => store,
},
};
},
inject: [ConfigService],
})您需要返回存储引用来创建方法,如下面的链接所示,有两种类型的存储这里,然后它应该可以工作
https://stackoverflow.com/questions/74536610
复制相似问题