Node version: v14.15.4
Nest-js version: 9.0.0
app.module.ts
Here is the code.
In the app module, I am registering Redis as a cache manager.
@Module({
imports: [
CacheModule.register({
isGlobal: true,
store: redisStore,
url: process.env.REDIS_URL,
})
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
service.ts
The cache data method is for storing data with a key. -> the problem is the set function doesn’t save anything
And get Data for returning the data by key.
@Injectable()
export class SomeService {
constructor(@Inject(CACHE_MANAGER) private cacheManager: Cache) {}
async cacheData(key: string, data): Promise<void> {
await this.cacheManager.set(key, data);
}
async getData(key: string, data): Promise<any> {
return this.cacheManager.get(key);
}
}
It doesn’t throw any error in runtime.
6
Answers
I am not sure why your getData function returns
Promise<void>
have you tried returningPromise<any>
or the data type you are expecting e.g.Promise<string>
. You could also try addingawait
.Are you sure that you are connecting to redis successfully ?. Have you tried adding password and tls (true/false) configuration ?
The default expiration time of the cache is 5 seconds.
To disable expiration of the cache, set the ttl configuration property to 0:
i has met the same problem as you,the way to fix this is using the install cmd to change the version of cache-manager-redis-store to 2.0.0 like ‘npm i [email protected]’
when you finish this step, the use of redisStore can be found,then the database can be linked.
I had the same problem.
It looks like NestJS v9 incompatible with version 5 of cache-manager. So you need to downgrade to v4 for now, until this issue is resolved: https://github.com/node-cache-manager/node-cache-manager/issues/210
Change your
package.json
to have this in the dependencies:Another commenter also suggested lowering the redis cache version.
Set the redis store as
redisStore.redisStore
(You will get an autocomplete)My stack:
redis.service.ts:
redis.module.ts:
This code works fine for me.