duanhuilao0787 2017-01-25 09:09 采纳率: 100%
浏览 13

我是否应该将缓存的数据保留在Web应用程序的内存中?

I have a database where products are kept.

There is also a list of categories.

Each product belongs to a category.

When a list of products updates, I run a function updateProductsCategories() that queries database, calculates a number of products in each category and returns a list like this:

Food:    20
Drinks:  74
Jackets: 15 

I use this list in a web page sidebar to show categories as links with amount of products in it.

My assumption is that I should run updateProductsCategories() as it is when products change, though not call it each time a page loads, but put its result in an in-memory object and get data from it to show on the page.

That way I will not make unnecessary db queries every time I show the page, but will use cached data and will have it always up-to-date as it's refreshed when products change.

As the object is not large, I don't think I need any additional solutions like Redis now.

Is it a correct and common way to optimize the app? Will it add speed to the app in real world?

  • 写回答

2条回答 默认 最新

  • douwen5951 2017-01-25 09:19
    关注

    If:

    • you need the stats frequently (number of products in each category)
      and / or acquiring the stats takes relatively long time / load
    • and product update is "infrequent" (compared to how frequently you need the stats)

    then yes, it is worth keeping it in memory. Every time a product is updated, you may invalidate the cached data and let it calculated again deferred (when it is needed) or calculate the new stats right away, after the update.

    Things to keep in mind:

    • access to these stats should be synchronized as web requests are served on multiple goroutines
    • if you have multiple server instances, these stats might become inaccurate; in this case you do need a central cache like Redis
    评论

报告相同问题?

悬赏问题

  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 matlab求解平差
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办
  • ¥15 vue2登录调用后端接口如何实现