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",[]);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。