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

PHP operates the class encapsulated by redies

Jul 25, 2016 am 08:43 AM

  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


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

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 Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

What are Enumerations (Enums) in PHP 8.1? What are Enumerations (Enums) in PHP 8.1? Apr 03, 2025 am 12:05 AM

The enumeration function in PHP8.1 enhances the clarity and type safety of the code by defining named constants. 1) Enumerations can be integers, strings or objects, improving code readability and type safety. 2) Enumeration is based on class and supports object-oriented features such as traversal and reflection. 3) Enumeration can be used for comparison and assignment to ensure type safety. 4) Enumeration supports adding methods to implement complex logic. 5) Strict type checking and error handling can avoid common errors. 6) Enumeration reduces magic value and improves maintainability, but pay attention to performance optimization.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

See all articles