【问题标题】:How to cache data?如何缓存数据?
【发布时间】:2020-08-17 20:00:40
【问题描述】:

我创建了两个函数,第一个 - Get 通过 id 从数据库中获取数据并缓存它,第二个 - POST 更新数据库中的数据。问题在于,我必须在获取后和更新后缓存。

谁能告诉我这是怎么做的?

我使用 NestJS,文档告诉我,缓存仅在 GET 控制器上工作。 https://docs.nestjs.com/techniques/caching

我的代码:

服务:

    async getUser(userID: number): Promise<UserEntity> {
        const user = await this.conn.getRepository(UserEntity).findOne(userID);

        return user;
    }

    
    async updateUser(userID: number, dto: UserEntityDto): Promise<ResultDTO> {
        const user = await this.conn.getRepository(UserEntity).findOne(configId);
        

       //all logic
    }

控制器:

@UseInterceptors(CacheInterceptor)
export class UserControleer{
    constructor(
        private readonly userService: UserService
    ){}

    @Get('/:userID')
    @CacheKey('custom_key')
    @CacheTTL(20)
    async getUser(
        @Param('userID') userID: number
    ): Promise<UserEntity> {
        return await this.userService.getUser(userID);
    }

    @Post('/:userID')
    async updateUser(
        @Param('userID') userID: number,
        @Body() dto: UserDTO
    ): Promise<ResultDTO> {
        return await this.userService.updateUser(userID, dto);
    }

感谢您的帮助。

【问题讨论】:

    标签: javascript node.js typescript caching nestjs


    【解决方案1】:

    TL;DR:您可能想要invalidate the cache entry,以便在下次调用时重新缓存它,或者在修改用户后更新缓存的条目。

    说明
    使用注解进行缓存通常用作拦截方法调用的代理。

    代理在配置的缓存中查找条目。匹配通常基于方法签名和方法参数。如果找到匹配项,将返回缓存的结果。

    理解这一点很重要,当找到匹配项时,底层方法不会被调用。这就是为什么我们不想缓存更新方法的原因,因为参数可能经常更改,并且应该始终执行更新。

    选项
    您的用例有很多选项,这里有两个:

    • 更新数据时使缓存条目失效;下次调用时重新缓存数据
    • 更新操作后更新缓存数据

    更多信息
    您可以在此 Stack Overflow 问题中找到有关管理缓存的更多信息: How to control cache in Nestjs?

    【讨论】:

      猜你喜欢
      • 2012-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多