PHP基于文件锁实现sqlite的并发操作

版权声明:转载请注明来源 https://blog.csdn.net/u013702678/article/details/87890228

sqlite简单好用,但是不支持多个进程的并行操作,即使并行的读也不行,出现并行读取,会出现database is locked错误。

如果多个进程操作同个sqlite库,通过随机重试可以规避掉一些并行的操作,但是在并发量大的情况下,还是不能完全规避掉并行的操作导致的失败。

完美的解决sqlite的并行操作,还得依靠锁机制,目前锁的实现有多钟方式,可以通过文件锁的方式实现,当然分布式锁也可以用在单机锁上,故redis锁、zookeeper锁等都是一种方案,总体对比,文件锁是最简单的一种方式,下面提供文件锁的一种实现。

<?php
class SqliteDataBaseTool
{
    private $db = null;
    private $lock_file;

    public function __construct($file_data,$lock_file)
    {
        $this->db = new \SQLite3($file_data);
        if (!$this->db) {
            throw new \Exception("SQLite3 construct failed,err:" . $this->db->lastErrorMsg());
        }

        $this->lock_file = $lock_file;
    }

    //日志实现,目前仅仅是echo输出
    protected function log($msg)
    {
        echo $msg.PHP_EOL;
    }

    public function __call($name, $arguments)
    {
        if(!method_exists($this,$name))
        {
            $name = "_".$name;
        }

        if(method_exists($this,$name))
        {
            if (!$fp = @fopen($this->lock_file, 'ab')) {
                $this->log("fopen $this->lock_file failed!!");
                return false;
            }

            if (flock($fp, LOCK_EX)) {
                $result = $this->$name($arguments[0],$arguments[1]);
                flock($fp, LOCK_UN);
            } else {
                fclose($fp);
                return false;
            }
            fclose($fp);
            return $result;
        } else {
            $this->log(__CLASS__." don't exist ".$name);
            throw new \Exception(__CLASS__." don't exist ".$name);
        }
    }

    protected function _insert($table,array $data)
    {
        echo "insert".PHP_EOL;
    }

    public function _query($table,array $where)
    {
        echo "query".PHP_EOL;
    }

    public function _delete($table,array $where)
    {
        echo "delete".PHP_EOL;
    }

    public function __destruct()
    {
        if($this->db!=null) {
            $this->db->close();
            unset($this->db);
        }
    }
}

$s = new SqliteDataBaseTool("/tmp/test.db","/tmp/test.lock");
$s->insert("t_test",[]);
$s->query("t_test",[]);
$s->delete("t_test",[]);

猜你喜欢

转载自blog.csdn.net/u013702678/article/details/87890228