LRU缓存是否防止Sentry创建多个实例?

huangapple go评论66阅读模式
英文:

Does LRU caching prevent sentry from creating multiple instances?

问题

我正在使用 Sentry 监控我的应用程序。初始化如下:

from functools import lru_cache
import sentry_sdk

@lru_cache
def start_sentry():
    sentry_instance = sentry_sdk.init(DSN)
    return sentry_instance

现在,如果我多次执行 start_sentry,实际上所有创建的多个 sentry_instance 都指向内存中的同一个对象。如果不使用 lru_cache 装饰器,会在内存中创建新的 Sentry 实例。所以我的问题是:使用 lru 缓存是否达到了我期望的效果,即尽管我尝试多次执行它,它是否只会初始化 Sentry 一次?

我使用的是 Python 3.6.7 和 sentry-sdk 版本 0.10.2。

英文:

I am using sentry to monitor my application. The initialization is done like thus:

from functools import lru_cache
import sentry_sdk

@lru_cache
def start_sentry():
    sentry_instance = sentry_sdk.init(DSN)
    return sentry_instance

Now, if i were to execute start_sentry multiple times, the multiple sentry_instances created are actually all pointing to the same object in memory. Without using the lru_cache decorator, new sentry instances are crated in memory. So my question is: is using lru caching doing what I am expecting, that is - will it only initialize sentry once even though i attempt to do it multiple times?

i am on python3.6.7 sentry-sdk==0.10.2

答案1

得分: 1

只要在相同进程中调用,它会像这样工作。

这是一个很大的假设。根据您的 Web 应用程序,工作进程可能会预先分叉,在这种情况下,缓存无法跨进程工作。

一个重现此情况的最小示例是:

from functools import lru_cache
from multiprocessing import Process


@lru_cache
def start_sentry():
    print("starting sentry")
    ...
    return


if __name__ == "__main__":
    proc1 = Process(target=start_sentry)
    proc1.start()
    proc1.join()
    proc2 = Process(target=start_sentry)
    proc2.start()
    proc2.join()

您将会看到在这段代码中会打印两次 "starting sentry",因为每个进程都有自己的缓存,它们无法相互通信。

英文:

It will work like that provided it's called within the same process.

That's a big if. Depending on your web application, workers might be pre-forked, and in this case the cache doesn't work across processes.

A minimal example to reproduce that is:

from functools import lru_cache
from multiprocessing import Process


@lru_cache
def start_sentry():
    print("starting sentry")
    ...
    return


if __name__ == "__main__":
    proc1 = Process(target=start_sentry)
    proc1.start()
    proc1.join()
    proc2 = Process(target=start_sentry)
    proc2.start()
    proc2.join()

You will see "starting sentry" printed twice with this code, because each process got its own cache and they have no way of talking to eachother.

huangapple
  • 本文由 发表于 2023年7月14日 09:43:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/76684221.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定