如果2个或更多服务器同时写入同一文件,NFS会发生什么情况? [英] What happens in NFS if 2 or more servers try to write the same file simultaneously?

查看:2763
本文介绍了如果2个或更多服务器同时写入同一文件,NFS会发生什么情况?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个能自动调整图像大小的PHP webapp,并且正在考虑将已缓存的副本存储在已安装NFS的NAS上,这样在更新图像时就可以轻松刷新缓存。



我唯一担心的是,如果群集中的两台或更多台服务器同时尝试创建相同的映像缓存文件,通常会发生什么情况?

当缓存刷新内容更新时,它们可能会发生碰撞,但是我没有很好的方法来测试这种情况因为我只是在一个盒子里工作。



有这方面经验的人吗?

解决方案

这取决于你如何打开文件。如果以append模式打开文件,那么Unix / Linux实际上会将内容写入缓存,直到您创建一个新行字符,然后将新行添加到文件末尾(覆盖文件结束字节模式)并写入新的文件结束。在这种情况下,如果两个人试图同时写入同一个文件,那么两个写入行都会通过,并按照接收到的顺序每次附上一行。因此,您可以期望如下所示:

 这是文件
的旧内容
第一个脚本(脚本1)
这行(脚本2)

在两个写命令几乎同时到达(精确到纳秒级)的情况下,操作系统实际上会创建一个中断状态。这是由操作系统如何处理这个,但大多数会产生两个随机数,以决定谁先走。



如果你打开文件在写模式说你想添加内容到中间),那么你实际上必须锁定文件来做到这一点。第二个PHP脚本会抛出一个错误,说它无法打开文件。


I'm working on a PHP webapp that does automatic resizing of images and I'm thinking of storing the cached copies on the NFS mounted NAS so it's easy for me to flush the cache when images are updated.

The only thing I'm worried about is what happens in general with NFS if 2 or more of the servers in the cluster are trying to create the same image cache file at the same time?

There's a pretty good chance that when the cache gets flushed for content updates that they could collide like that, but I don't have a great way to test this scenario in development because I'm only working on a single box.

Anyone with experience on this?

解决方案

It depends on how you open the file. If you open the file in "append" mode then Unix/Linux will actually write the contents to a cache until you create a new-line character, then it sticks the new line on to the end of the file (over-writing the "end-of-file" byte pattern) and writes a new "end-of-file". In this case if two people try to write to the same file simultaneously then both of the write lines will go through, attaching themselves one line at a time in the order that they were received. Thus you could expect something like:

This was the old contents
of the file
The first script added
The second script added
this line (script 1)
this line (script 2)

In the rare chance that two "write" commands arrive at EXACTLY the same time (down to nanosecond precision) then the Operating System actually creates an interrupt state. It's up to the OS how it handles this, but most will just generate two random numbers to decide who goes first.

If you open the file in "write" mode (say you wanted to add content to the middle) then you actually have to lock the file to do this. The second PHP script will throw an error saying that it couldn't open the file.

这篇关于如果2个或更多服务器同时写入同一文件,NFS会发生什么情况?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆