Skip to content

How to flock file when used Storage::put write content to local file? #34411

Answered by cgfeel
cgfeel asked this question in General
Discussion options

You must be logged in to vote

I added a service object, solve it by Redis, like this:

<?php
namespace App\Services\Site;

use Illuminate\Support\Facades\Storage;

/**
 * 给`Storage`本地存储通过redis队列方式加上锁,防止并发
 * @思路:
 *  - 每次请求一个服务对象时会自动注册一个token加入队列
 *  - 读写文件前会检查当前token是否是队列中第一个来决定执行还是等待执行
 * 
 * @为什么不用flock文件锁,使用fopen给资源上锁有几个问题:
 *  - 如果用模式`w+`,读写锁打开文件时之前的数据将被清空
 *  - 如果用模式`r+`,读写锁打开文件时指针指向文件头,如果写入的数据比之前少会造成文件破坏
 *  - 如果用模式`a+`,只能追加`log`,不能更新json
 *  - 如果读写锁分开执行,可能会并发造成当前读取的数据和最新写入的数据不一致,当二次写入造成回档
 * 
 * @关于锁回收:
 *  - 对象销毁后自动回收,或通过`unlock`手动回收
 *  - 如果执行一个慢请求的时候会造成后面资源堵塞,建议完成后手动回收
 *  - 锁回收后需要再次读写文件会重新加入队列
 *  - 锁还未回收手动通过`lock`后,也会重新加入队列
 *  - 通过单例请求对象方法并没用对象引用,会在方法请求完之后立即回收锁
 */
class StorageService 
{
    const NAME =…

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by cgfeel
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
1 participant