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 and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

How does PHP handle object cloning (clone keyword) and the __clone magic method?How does PHP handle object cloning (clone keyword) and the __clone magic method?Apr 17, 2025 am 12:24 AM

In PHP, use the clone keyword to create a copy of the object and customize the cloning behavior through the \_\_clone magic method. 1. Use the clone keyword to make a shallow copy, cloning the object's properties but not the object's properties. 2. The \_\_clone method can deeply copy nested objects to avoid shallow copying problems. 3. Pay attention to avoid circular references and performance problems in cloning, and optimize cloning operations to improve efficiency.

PHP vs. Python: Use Cases and ApplicationsPHP vs. Python: Use Cases and ApplicationsApr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor