1 <?php
2
3 /**
4 * 使用php提供检查扩展是否存在的函数来进行判断,调用对应的扩展来使用api
5 */
6 class Mem
7 {
8 private $handle = null; // 连接实例
9 private $so = true; // 检查扩展是否存在
10
11 /**
12 * 初始化链接
13 * @param array $hosts 链接配置
14 * @param string $preFix 前缀
15 */
16 public function __construct(array $hosts, string $preFix = '')
17 {
18 // 检查给定的类是否存在
19 $this->so = extension_loaded('Memcached');
20 if ($this->so) {
21 $this->handle = new Memcached();
22 } else {
23 $this->handle = new Memcache();
24 }
25
26 //配置
27 $c = $this->so ? '\\Memcached' : '\\Memcache';
28 // 1. 一致性hash算法
29 $params = [
30 $c::OPT_DISTRIBUTION => $c::DISTRIBUTION_CONSISTENT,
31 $c::OPT_LIBKETAMA_COMPATIBLE => true,
32 $c::OPT_REMOVE_FAILED_SERVERS => true
33 ];
34 // 2. 前缀
35 $preFix && $params[$c::OPT_PREFIX_KEY] = $preFix;
36 $this->handle->setOptions($params);
37
38 // 连接memcached服务
39 foreach ($hosts as $item) {
40 [$host, $port] = $item;
41 $this->handle->addServer($host, $port);
42 }
43 }
44
45 /**
46 * 获取
47 */
48 public function get(string $key)
49 {
50 return $this->handle->get($key);
51 }
52
53 /**
54 * 添加与设置
55 */
56 public function set(string $key, $value, int $expire = 3600)
57 {
58 if ($this->so) {
59 $this->handle->set($key, $value, $expire);
60 } else {
61 $this->handle->set($key, $value, MEMCACHE_COMPRESSED, $expire);
62 }
63 }
64
65 /**
66 * 删除
67 */
68 public function del(string $key)
69 {
70 return $this->handle->delete($key);
71 }
72
73 /**
74 * 自增操作
75 * @param $key
76 * @param $value
77 * @return mixed
78 */
79 public function incr($key, $value = 1)
80 {
81 if (!$key) return false;
82 return $this->handle->increment($key, $value);
83 }
84
85 /**
86 * 自减操作
87 * @param $key
88 * @param $value
89 * @return mixed
90 */
91 public function decr($key, $value = 1)
92 {
93 if (!$key) return false;
94 return $this->handle->decrement($key, $value);
95 }
96
97 /**
98 * 全部删除
99 */
100 public function flush()
101 {
102 return $this->handle->flush();
103 }
104 }
105
106 // 单个/集群设置
107 $hosts = [
108 ['127.0.0.1', 11211],
109 ['127.0.0.1', 11212],
110 ['127.0.0.1', 11213],
111 ['127.0.0.1', 11214]
112 ];
113 $mem = new Mem($hosts);
114 // 操作
115 for ($i = 1; $i <= 12; $i++) {
116 $mem->set('key_' . $i, 'value_' . $i);
117 }
118 // $mem->flush();