search
HomeBackend DevelopmentPHP TutorialPHP operates the class encapsulated by redies

  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_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_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 return $this->_linkHandle['slave'][0];
  194. }
  195. // 随机 Hash 得到 Slave 的句柄
  196. $hash = $this->_hashId(mt_rand(), $this->_sn);
  197. return $this->_linkHandle['slave'][$hash];
  198. }
  199. /**
  200. * Get the value between 0~m-1 after hashing based on ID
  201. *
  202. * @param string $id
  203. * @param int $m
  204. * @return int
  205. */
  206. private function _hashId($id,$m=10)
  207. {
  208. //把字符串K转换为 0~m-1 之间的一个值作为对应记录的散列地址
  209. $k = md5($id);
  210. $l = strlen($k);
  211. $b = bin2hex($k);
  212. $h = 0;
  213. for($i=0;$i {
  214. //相加模式HASH
  215. $h += substr($b,$i*2,2);
  216. }
  217. $hash = ($h*1)%$m;
  218. return $hash;
  219. }
  220. /**
  221. * lpush
  222. */
  223. public function lpush($key,$value){
  224. return $this->getRedis()->lpush($key,$value);
  225. }
  226. /**
  227. * add lpop
  228. */
  229. public function lpop($key){
  230. return $this->getRedis()->lpop($key);
  231. }
  232. /**
  233. * lrange
  234. */
  235. public function lrange($key,$start,$end){
  236. return $this->getRedis()->lrange($key,$start,$end);
  237. }
  238. /**
  239. * set hash opeation
  240. */
  241. public function hset($name,$key,$value){
  242. if(is_array($value)){
  243. return $this->getRedis()->hset($name,$key,serialize($value));
  244. }
  245. return $this->getRedis()->hset($name,$key,$value);
  246. }
  247. /**
  248. * get hash opeation
  249. */
  250. public function hget($name,$key = null,$serialize=true){
  251. if($key){
  252. $row = $this->getRedis()->hget($name,$key);
  253. if($row && $serialize){
  254. unserialize($row);
  255. }
  256. return $row;
  257. }
  258. return $this->getRedis()->hgetAll($name);
  259. }
  260. /**
  261. * delete hash opeation
  262. */
  263. public function hdel($name,$key = null){
  264. if($key){
  265. return $this->getRedis()->hdel($name,$key);
  266. }
  267. return $this->getRedis()->hdel($name);
  268. }
  269. /**
  270. * Transaction start
  271. */
  272. public function multi(){
  273. return $this->getRedis()->multi();
  274. }
  275. /**
  276. * Transaction send
  277. */
  278. public function exec(){
  279. return $this->getRedis()->exec();
  280. }
  281. }// End Class
  282. // ================= TEST DEMO =================
  283. // 只有一台 Redis 的应用
  284. $redis = new RedisCluster();
  285. $redis->connect(array('host'=>'127.0.0.1','port'=>6379));
  286. //*
  287. $cron_id = 10001;
  288. $CRON_KEY = 'CRON_LIST'; //
  289. $PHONE_KEY = 'PHONE_LIST:'.$cron_id;//
  290. //cron info
  291. $cron = $redis->hget($CRON_KEY,$cron_id);
  292. if(empty($cron)){
  293. $cron = array('id'=>10,'name'=>'jackluo');//mysql data
  294. $redis->hset($CRON_KEY,$cron_id,$cron); // set redis
  295. }
  296. //phone list
  297. $phone_list = $redis->lrange($PHONE_KEY,0,-1);
  298. print_r($phone_list);
  299. if(empty($phone_list)){
  300. $phone_list =explode(',','13228191831,18608041585'); //mysql data
  301. //join list
  302. if($phone_list){
  303. $redis->multi();
  304. foreach ($phone_list as $phone) {
  305. $redis->lpush($PHONE_KEY,$phone);
  306. }
  307. $redis->exec();
  308. }
  309. }
  310. print_r($phone_list);
  311. /*$list = $redis->hget($cron_list,);
  312. var_dump($list);*/
  313. //*/
  314. //$redis->set('id',35);
  315. /*
  316. $redis->lpush('test','1111');
  317. $redis->lpush('test','2222');
  318. $redis->lpush('test','3333');
  319. $list = $redis->lrange('test',0,-1);
  320. print_r($list);
  321. $lpop = $redis->lpop('test');
  322. print_r($lpop);
  323. $lpop = $redis->lpop('test');
  324. print_r($lpop);
  325. $lpop = $redis->lpop('test');
  326. print_r($lpop);
  327. */
  328. // var_dump($redis->get('id'));
复制代码

php, redies


Statement
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
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools