简体   繁体   English

从多个进程访问缓存时我们是否需要线程安全(Redis)

[英]Do we need thread safety when Cache is accessed from multiple processes (Redis)

I know what thread safety is.我知道什么是线程安全。 And in some scenarios it makes perfect senses.在某些情况下,它具有完美的意义。 For instance, I understand that logger need to be thread safe, otherwise it might try to open the same file and access it (when access from multiple threads).例如,我知道记录器需要是线程安全的,否则它可能会尝试打开同一个文件并访问它(从多个线程访问时)。

But I cannot visualize, why thread safety is important in while accessing cache.但我无法想象,为什么在访问缓存时线程安全很重要。 How can get/set from multiple thread can corrupt cache.如何从多线程获取/设置会破坏缓存。

And most important, if thread safety is required (while accessing cache), how can we use it when cache is accessed from multiple processes.最重要的是,如果需要线程安全(在访问缓存时),当从多个进程访问缓存时我们如何使用它。 It would be nice if someone can answer in context of Redis.如果有人可以在 Redis 的上下文中回答,那就太好了。

Thanks In Advance提前致谢

Redis is single-threaded. Redis 是单线程的。 As such all commands in Redis are atomic.因此,Redis 中的所有命令都是原子的。 However, depending on the implementation in the client library sharing a connection may still be problematic.但是,根据客户端库中的实现,共享连接可能仍然存在问题。 There would be the potential for reads and writes to be out of sequence such that one thread could get the read another thread was supposed to get causing problems in the client side.读取和写入可能会乱序,这样一个线程可能会读取另一个线程应该得到的读取,从而导致客户端出现问题。 This could cause corruption by missing writes or invalid responses causing rewrites.这可能会因丢失写入或导致重写的无效响应而导致损坏。

Thus the concern is not so much corrupting the data in Redis but leaking the data on the client side.因此,担心的不是破坏 Redis 中的数据,而是泄漏客户端的数据。 Think of a shopping cart with someone else's items being charged to you as an example.以购物车为例,向您收取其他人的商品。 For this reason, among others, your client access needs be be thread safe.出于这个原因,除其他外,您的客户端访问需要是线程安全的。

Although I have not got any direct text regarding it.虽然我没有得到任何关于它的直接文本。 But it seems, locking (or other way for synchronization) is applied on server end.但似乎在服务器端应用了锁定(或其他同步方式)。 And it make sure data is not corrupted from multiple threads/processes.并且它确保数据不会被多个线程/进程损坏。

And why it is important fro make client libraries thread safe, is because they write/read on TCP connection (via network stream I guess).为什么使客户端库线程安全很重要,是因为它们在 TCP 连接上写入/读取(我猜是通过网络流)。 And it is important that if same client is used by multiple thread, it should work fine (in case client is thread safe), otherwise it will be document that, client should not shared among multiple thread.并且重要的是,如果多个线程使用同一个客户端,它应该可以正常工作(如果客户端是线程安全的),否则将记录在案,客户端不应在多个线程之间共享。

I am not marking this as a correct answer.我没有将此标记为正确答案。 If people up vote this and agree on that, then I will do that.如果人们对此投票并同意,那么我会这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM