Home > Backend Development > PHP Tutorial > PHP operates the class encapsulated by redies

PHP operates the class encapsulated by redies

WBOY
Release: 2016-07-25 08:43:02
Original
802 people have browsed it
  1. /**
  2. * Redis operation, supporting Master/Slave load cluster
  3. *
  4. * @author jackluo
  5. */
  6. class RedisCluster{
  7. // Whether to use the M/S read-write cluster solution
  8. private $_isUseCluster = false;
  9. // Slave handle tag
  10. private $_sn = 0;
  11. // Server connection handle
  12. private $_linkHandle = array(
  13. 'master'=>null,// Only supports one Master
  14. 'slave'=>array(),// Yes There are multiple Slave
  15. );
  16. /**
  17. * Constructor
  18. *
  19. * @param boolean $isUseCluster Whether to use the M/S scheme
  20. */
  21. public function __construct($isUseCluster=false){
  22. $this->_isUseCluster = $isUseCluster;
  23. }
  24. /**
  25. * Connect to the server, note: long connections are used here to improve efficiency, but will not automatically close
  26. *
  27. * @param array $config Redis server configuration
  28. * @param boolean $isMaster Whether the currently added server is a Master server
  29. * @ return boolean
  30. * /
  31. public function connect($config=array('host'=>'127.0.0.1','port'=>6379), $isMaster=true){
  32. // default port
  33. if(!isset($ config['port'])){
  34. $config['port'] = 6379;
  35. }
  36. // Set Master connection
  37. if($isMaster){
  38. $this->_linkHandle['master'] = new Redis ();
  39. $ret = $this->_linkHandle['master']->pconnect($config['host'],$config['port']);
  40. }else{
  41. // Multiple Slave Connection
  42. $this->_linkHandle['slave'][$this->_sn] = new Redis();
  43. $ret = $this->_linkHandle['slave'][$this->_sn] ->pconnect($config['host'],$config['port']);
  44. ++$this->_sn;
  45. }
  46. return $ret;
  47. }
  48. /**
  49. * Close connection
  50. *
  51. * @param int $flag Close selection 0: Close Master 1: Close Slave 2: Close all
  52. * @return boolean
  53. * /
  54. public function close($flag=2){
  55. switch($flag){
  56. // Close Master
  57. case 0:
  58. $this->getRedis()->close();
  59. break;
  60. // Close Slave
  61. case 1:
  62. for($i=0; $i<$this->_sn; ++$i){
  63. $this->_linkHandle['slave'][$i]->close ();
  64. }
  65. break;
  66. // Close all
  67. case 1:
  68. $this->getRedis()->close();
  69. for($i=0; $i<$this->_sn ; ++$i){
  70. $this->_linkHandle['slave'][$i]->close();
  71. }
  72. break;
  73. }
  74. return true;
  75. }
  76. /**
  77. * Get the original Redis object to have more operations
  78. *
  79. * @param boolean $isMaster Returns the type of server true: Returns Master false: Returns Slave
  80. * @param boolean $slaveOne Returns Slave selection true: Load balancing returns randomly A Slave selection false: Return all Slave selections
  81. * @return redis object
  82. */
  83. public function getRedis($isMaster=true,$slaveOne=true){
  84. // Only return Master
  85. if($isMaster){
  86. return $this->_linkHandle['master'];
  87. }else{
  88. return $slaveOne ? $this->_getSlaveRedis() : $this->_linkHandle['slave'];
  89. }
  90. }
  91. /**
  92. * Write cache
  93. *
  94. * @param string $key group storage KEY
  95. * @param string $value cache value
  96. * @param int $expire expiration time, 0: means no expiration time
  97. */
  98. public function set($key, $value , $expire=0){
  99. // Never timeout
  100. if($expire == 0){
  101. $ret = $this->getRedis()->set($key, $value);
  102. }else {
  103. $ret = $this->getRedis()->setex($key, $expire, $value);
  104. }
  105. return $ret;
  106. }
  107. /**
  108. * Read cache
  109. *
  110. * @param string $key Cache KEY, support fetching multiple $keys at one time = array('key1','key2')
  111. * @return string || boolean Return false on failure, return string on success
  112. */
  113. public function get($key){
  114. // Whether to get multiple values ​​at once
  115. $func = is_array($key) ? 'mGet' : 'get';
  116. // No M/S is used
  117. if(! $this-> _isUseCluster){
  118. return $this->getRedis()->{$func}($key);
  119. }
  120. // 使用了 M/S
  121. return $this->_getSlaveRedis()->{$func}($key);
  122. }
  123. /*
  124. // magic function
  125. public function __call($name,$arguments){
  126. return call_user_func($name,$arguments);
  127. }
  128. */
  129. /**
  130. * Conditional form to set the cache. If the key does not exist, it will be set. If it exists, the setting will fail.
  131. *
  132. * @param string $key cache KEY
  133. * @param string $value cache value
  134. * @return boolean
  135. */
  136. public function setnx($key, $value){
  137. return $this->getRedis()->setnx($key, $value);
  138. }
  139. /**
  140. * Delete cache
  141. *
  142. * @param string || array $key cache KEY, supports single key: "key1" or multiple keys: array('key1','key2')
  143. * @return int deleted key Quantity
  144. */
  145. public function remove($key){
  146. // $key => "key1" || array('key1','key2')
  147. return $this->getRedis()->delete($key);
  148. }
  149. /**
  150. * Value addition operation, similar to ++$i, if the key does not exist, it is automatically set to 0 and then the addition operation is performed
  151. *
  152. * @param string $key Cache KEY
  153. * @param int $default The default value during operation
  154. * @return int Value after operation
  155. */
  156. public function incr($key,$default=1){
  157. if($default == 1){
  158. return $this->getRedis()->incr($key);
  159. }else{
  160. return $this->getRedis()->incrBy($key, $default);
  161. }
  162. }
  163. /**
  164. * Value subtraction operation, similar to --$i, if the key does not exist, it will be automatically set to 0 and then subtracted.
  165. *
  166. * @param string $key Cache KEY
  167. * @param int $default Default value during operation
  168. * @return int Value after operation
  169. */
  170. public function decr($key,$default=1){
  171. if($default == 1){
  172. return $this->getRedis()->decr($key);
  173. }else{
  174. return $this->getRedis()->decrBy($key, $default);
  175. }
  176. }
  177. /**
  178. * Empty the current database
  179. *
  180. * @return boolean
  181. */
  182. public function clear(){
  183. return $this->getRedis()->flushDB();
  184. }
  185. /* =================== 以下私有方法 =================== */
  186. /**
  187. * Random HASH to get the Redis Slave server handle
  188. *
  189. * @return redis object
  190. */
  191. private function _getSlaveRedis(){
  192. // 就一台 Slave 机直接返回
  193. if($this->_sn <= 1){
  194. return $this->_linkHandle['slave'][0];
  195. }
  196. // 随机 Hash 得到 Slave 的句柄
  197. $hash = $this->_hashId(mt_rand(), $this->_sn);
  198. return $this->_linkHandle['slave'][$hash];
  199. }
  200. /**
  201. * Get the value between 0~m-1 after hashing based on ID
  202. *
  203. * @param string $id
  204. * @param int $m
  205. * @return int
  206. */
  207. private function _hashId($id,$m=10)
  208. {
  209. //把字符串K转换为 0~m-1 之间的一个值作为对应记录的散列地址
  210. $k = md5($id);
  211. $l = strlen($k);
  212. $b = bin2hex($k);
  213. $h = 0;
  214. for($i=0;$i<$l;$i++)
  215. {
  216. //相加模式HASH
  217. $h += substr($b,$i*2,2);
  218. }
  219. $hash = ($h*1)%$m;
  220. return $hash;
  221. }
  222. /**
  223. * lpush
  224. */
  225. public function lpush($key,$value){
  226. return $this->getRedis()->lpush($key,$value);
  227. }
  228. /**
  229. * add lpop
  230. */
  231. public function lpop($key){
  232. return $this->getRedis()->lpop($key);
  233. }
  234. /**
  235. * lrange
  236. */
  237. public function lrange($key,$start,$end){
  238. return $this->getRedis()->lrange($key,$start,$end);
  239. }
  240. /**
  241. * set hash opeation
  242. */
  243. public function hset($name,$key,$value){
  244. if(is_array($value)){
  245. return $this->getRedis()->hset($name,$key,serialize($value));
  246. }
  247. return $this->getRedis()->hset($name,$key,$value);
  248. }
  249. /**
  250. * get hash opeation
  251. */
  252. public function hget($name,$key = null,$serialize=true){
  253. if($key){
  254. $row = $this->getRedis()->hget($name,$key);
  255. if($row && $serialize){
  256. unserialize($row);
  257. }
  258. return $row;
  259. }
  260. return $this->getRedis()->hgetAll($name);
  261. }
  262. /**
  263. * delete hash opeation
  264. */
  265. public function hdel($name,$key = null){
  266. if($key){
  267. return $this->getRedis()->hdel($name,$key);
  268. }
  269. return $this->getRedis()->hdel($name);
  270. }
  271. /**
  272. * Transaction start
  273. */
  274. public function multi(){
  275. return $this->getRedis()->multi();
  276. }
  277. /**
  278. * Transaction send
  279. */
  280. public function exec(){
  281. return $this->getRedis()->exec();
  282. }
  283. }// End Class
  284. // ================= TEST DEMO =================
  285. // 只有一台 Redis 的应用
  286. $redis = new RedisCluster();
  287. $redis->connect(array('host'=>'127.0.0.1','port'=>6379));
  288. //*
  289. $cron_id = 10001;
  290. $CRON_KEY = 'CRON_LIST'; //
  291. $PHONE_KEY = 'PHONE_LIST:'.$cron_id;//
  292. //cron info
  293. $cron = $redis->hget($CRON_KEY,$cron_id);
  294. if(empty($cron)){
  295. $cron = array('id'=>10,'name'=>'jackluo');//mysql data
  296. $redis->hset($CRON_KEY,$cron_id,$cron); // set redis
  297. }
  298. //phone list
  299. $phone_list = $redis->lrange($PHONE_KEY,0,-1);
  300. print_r($phone_list);
  301. if(empty($phone_list)){
  302. $phone_list =explode(',','13228191831,18608041585'); //mysql data
  303. //join list
  304. if($phone_list){
  305. $redis->multi();
  306. foreach ($phone_list as $phone) {
  307. $redis->lpush($PHONE_KEY,$phone);
  308. }
  309. $redis->exec();
  310. }
  311. }
  312. print_r($phone_list);
  313. /*$list = $redis->hget($cron_list,);
  314. var_dump($list);*/
  315. //*/
  316. //$redis->set('id',35);
  317. /*
  318. $redis->lpush('test','1111');
  319. $redis->lpush('test','2222');
  320. $redis->lpush('test','3333');
  321. $list = $redis->lrange('test',0,-1);
  322. print_r($list);
  323. $lpop = $redis->lpop('test');
  324. print_r($lpop);
  325. $lpop = $redis->lpop('test');
  326. print_r($lpop);
  327. $lpop = $redis->lpop('test');
  328. print_r($lpop);
  329. */
  330. // var_dump($redis->get('id'));
复制代码

php, redies


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template