PHP队列原理及基于队列的写文件案例

队列是一种线性表,按照先进先出的原则进行的:

入队:

出队:

PHP实现队列:第一个元素作为队头,最后一个元素作为队尾

1
2
3
4
5
6
7
8
9
<?php
/**
 * 队列就是这么简单
 *
 * @link
 */
$array = array('PHP', 'JAVA');
array_push($array, 'PYTHON'); //入队列
array_shift($array); //出队列

什么是双端队列(或双向队列)Deque,全名double-ended queue?

即元素可以在队列的任意一段入队或出队,如果我们把这些方法叫做insertLeft()和insertRight(),以及removeLeft()和removeRight()。如果严格禁止调用insertLeft()和removeLeft()方法(或禁用右段的操作),双端队列功能就和栈一样。禁止调用insertLeft()和removeRight()(或相反的另一对方法),它的功能就和队列一样了。双端队列与栈或队列相比,是一种多用途的数据结构。

PHP实现双端队列

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
<?php
class Deque
{
  public $queue = array();
  /**(尾部)入队 **/
  public function addLast($value)
  {
    return array_push($this->queue,$value);
  }
  /**(尾部)出队**/
  public function removeLast()
  {
    return array_pop($this->queue);
  }
  /**(头部)入队**/
  public function addFirst($value)
  {
    return array_unshift($this->queue,$value);
  }
  /**(头部)出队**/
  public function removeFirst()
  {
    return array_shift($this->queue);
  }
  /**清空队列**/
  public function makeEmpty()
  {
    unset($this->queue);
  }
  /**获取列头**/
  public function getFirst()
  {
    return reset($this->queue);
  }
  /** 获取列尾 **/
  public function getLast()
  {
    return end($this->queue);
  }
  /** 获取长度 **/
  public function getLength()
  {
    return count($this->queue);
  }
}

队列的用途:

队列可以很好地异步处理数据传送和存储,当你频繁地向数据库中插入数据、频繁地向搜索引擎提交数据,就可采取队列来异步插入。另外,还可以将较慢的处理逻辑、有并发数量限制的处理逻辑,通过消息队列放在后台处理,例如FLV视频转换、发送手机短信、发送电子邮件等。

项目案例

这里有个项目,因为服务器权限问题,没办法安装安装队列程序,而且并发300+,服务商的数据库最大连接数是300,为了解决这个问题所以编写了一个简单的队列程序,代码如下

读队列代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<?php
set_time_limit(0);
$file_name3 = '3.txt';//这个地方是讲队列文件读出的内容写入文件,test中代替的是mysql数据库操作
$file3 = fopen($file_name3,'a');
while(true)
{
  $c = FALSE;
  $file_name = '1.txt';//队列文件
  $file = fopen($file_name,'r');
  if(!feof($f))
  {
    //获得第一条数据
    $a = fgets($file);
    if(!empty($a))
    {
      $c = TRUE;
      fwrite($file3,$a);//这里可以改为数据库操作
    }
  }
  fclose($file);
  if($c)
  {
    //将文件的第一条数据删除
    exec('sed -i \'1d\' /var/www/csv_sql/1.txt');
  }
  sleep(1);
  if(time()>=strtotime('20160416150000'))
  {
    exit;
  }
}
fclose($file3);

读队列程序其实就是一个死循环程序,如不设置关闭点,则一直循环读取文件

写入队列程序比较简单,就是写文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?php
set_time_limit(0);
$file_name2 = '2.txt';//test中用来比对队列程序是否正常的
$file2 = fopen($file_name2,'a');
for($i=1;$i<11;$i++)
{
  $file_name = '1.txt';//队列文件
  $file = fopen($file_name,'a');//fopen的mode属性必须是a或a+
  $str = $i.'--'.rand(100001,999999);
  fwrite($file,$str."\n");
  fwrite($file2,$str."\n");
  sleep(1);
  fclose($file);
}
fclose($file2);
posted @ 2018-04-13 17:10  改天打老虎  阅读(593)  评论(0编辑  收藏  举报