Concurrent.php
2.11 KB
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
<?php
/**
* User: haisheng.shen@yoho.cn
* Date: 15-2-9 下午2:08
*/
namespace LibModels;
class Concurrent
{
/**
* 添加并行的请求
* @param $url
* @param $method
* @param callable $callback
* @param null $errorCallback
*/
public static function call($url, $method, array $parameters = array(), callable $callback = null, callable $errorCallback=null)
{
\Yar_Concurrent_Client::call($url, $method, $parameters, $callback, $errorCallback);
}
/**
* 发起请求
* @param null $callback
* @param null $errorCallback
*/
public static function loop(callable $callback=null, callable $errorCallback=null)
{
\Yar_Concurrent_Client::loop($callback, $errorCallback);
}
/**
* 非并行yar实例的数组
* @var array
*/
protected static $yarInstance = array();
/**
* 非并行yar的实例
* @param $url
* @return mixed
*/
public static function single($url, $method, array $parameters =array(), callable $callback=null, callable $errorCallback = null)
{
$key = md5($url);
if (!isset(self::$yarInstance[$key])) {
self::$yarInstance[$key] = new \Yar_Client($url);
}
try {
$result = call_user_func_array(array(self::$yarInstance[$key], $method), $parameters);
$callback($result);
} catch (\Yar_Server_Exception $e) {
if (!empty($errorCallback)) {
$errorCallback($e);
}
}
}
/**
* 根据参数来选择并行或者非并行
* @param $url
* @param $method
* @param array $params
* @param callable $callback
* @param callable $errorCallback
* @param bool $concurrent
*/
public static function choise($url, $method, array $params=array(), callable $callback=null, callable $errorCallback = null, $concurrent=true)
{
if ($concurrent) {
self::call($url, $method, $params, $callback, $errorCallback);
} else {
self::single($url, $method, $params, $callback, $errorCallback);
}
}
}