国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

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

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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)

How do I implement authentication and authorization in PHP? How do I implement authentication and authorization in PHP? Jun 20, 2025 am 01:03 AM

TosecurelyhandleauthenticationandauthorizationinPHP,followthesesteps:1.Alwayshashpasswordswithpassword_hash()andverifyusingpassword_verify(),usepreparedstatementstopreventSQLinjection,andstoreuserdatain$_SESSIONafterlogin.2.Implementrole-basedaccessc

How can you handle file uploads securely in PHP? How can you handle file uploads securely in PHP? Jun 19, 2025 am 01:05 AM

To safely handle file uploads in PHP, the core is to verify file types, rename files, and restrict permissions. 1. Use finfo_file() to check the real MIME type, and only specific types such as image/jpeg are allowed; 2. Use uniqid() to generate random file names and store them in non-Web root directory; 3. Limit file size through php.ini and HTML forms, and set directory permissions to 0755; 4. Use ClamAV to scan malware to enhance security. These steps effectively prevent security vulnerabilities and ensure that the file upload process is safe and reliable.

What are the differences between == (loose comparison) and === (strict comparison) in PHP? What are the differences between == (loose comparison) and === (strict comparison) in PHP? Jun 19, 2025 am 01:07 AM

In PHP, the main difference between == and == is the strictness of type checking. ==Type conversion will be performed before comparison, for example, 5=="5" returns true, and ===Request that the value and type are the same before true will be returned, for example, 5==="5" returns false. In usage scenarios, === is more secure and should be used first, and == is only used when type conversion is required.

How do I perform arithmetic operations in PHP ( , -, *, /, %)? How do I perform arithmetic operations in PHP ( , -, *, /, %)? Jun 19, 2025 pm 05:13 PM

The methods of using basic mathematical operations in PHP are as follows: 1. Addition signs support integers and floating-point numbers, and can also be used for variables. String numbers will be automatically converted but not recommended to dependencies; 2. Subtraction signs use - signs, variables are the same, and type conversion is also applicable; 3. Multiplication signs use * signs, which are suitable for numbers and similar strings; 4. Division uses / signs, which need to avoid dividing by zero, and note that the result may be floating-point numbers; 5. Taking the modulus signs can be used to judge odd and even numbers, and when processing negative numbers, the remainder signs are consistent with the dividend. The key to using these operators correctly is to ensure that the data types are clear and the boundary situation is handled well.

How can you interact with NoSQL databases (e.g., MongoDB, Redis) from PHP? How can you interact with NoSQL databases (e.g., MongoDB, Redis) from PHP? Jun 19, 2025 am 01:07 AM

Yes, PHP can interact with NoSQL databases like MongoDB and Redis through specific extensions or libraries. First, use the MongoDBPHP driver (installed through PECL or Composer) to create client instances and operate databases and collections, supporting insertion, query, aggregation and other operations; second, use the Predis library or phpredis extension to connect to Redis, perform key-value settings and acquisitions, and recommend phpredis for high-performance scenarios, while Predis is convenient for rapid deployment; both are suitable for production environments and are well-documented.

How do I stay up-to-date with the latest PHP developments and best practices? How do I stay up-to-date with the latest PHP developments and best practices? Jun 23, 2025 am 12:56 AM

TostaycurrentwithPHPdevelopmentsandbestpractices,followkeynewssourceslikePHP.netandPHPWeekly,engagewithcommunitiesonforumsandconferences,keeptoolingupdatedandgraduallyadoptnewfeatures,andreadorcontributetoopensourceprojects.First,followreliablesource

What is PHP, and why is it used for web development? What is PHP, and why is it used for web development? Jun 23, 2025 am 12:55 AM

PHPbecamepopularforwebdevelopmentduetoitseaseoflearning,seamlessintegrationwithHTML,widespreadhostingsupport,andalargeecosystemincludingframeworkslikeLaravelandCMSplatformslikeWordPress.Itexcelsinhandlingformsubmissions,managingusersessions,interacti

How to set PHP time zone? How to set PHP time zone? Jun 25, 2025 am 01:00 AM

TosettherighttimezoneinPHP,usedate_default_timezone_set()functionatthestartofyourscriptwithavalididentifiersuchas'America/New_York'.1.Usedate_default_timezone_set()beforeanydate/timefunctions.2.Alternatively,configurethephp.inifilebysettingdate.timez

See all articles