搜索
首页后端开发php教程php操作redies封装的类

  1. /**
  2. * Redis 操作,支持 Master/Slave 的负载集群
  3. *
  4. * @author jackluo
  5. */
  6. class RedisCluster{
  7. // 是否使用 M/S 的读写集群方案
  8. private $_isUseCluster = false;
  9. // Slave 句柄标记
  10. private $_sn = 0;
  11. // 服务器连接句柄
  12. private $_linkHandle = array(
  13. 'master'=>null,// 只支持一台 Master
  14. 'slave'=>array(),// 可以有多台 Slave
  15. );
  16. /**
  17. * 构造函数
  18. *
  19. * @param boolean $isUseCluster 是否采用 M/S 方案
  20. */
  21. public function __construct($isUseCluster=false){
  22. $this->_isUseCluster = $isUseCluster;
  23. }
  24. /**
  25. * 连接服务器,注意:这里使用长连接,提高效率,但不会自动关闭
  26. *
  27. * @param array $config Redis服务器配置
  28. * @param boolean $isMaster 当前添加的服务器是否为 Master 服务器
  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. // 设置 Master 连接
  37. if($isMaster){
  38. $this->_linkHandle['master'] = new Redis();
  39. $ret = $this->_linkHandle['master']->pconnect($config['host'],$config['port']);
  40. }else{
  41. // 多个 Slave 连接
  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. * 关闭连接
  50. *
  51. * @param int $flag 关闭选择 0:关闭 Master 1:关闭 Slave 2:关闭所有
  52. * @return boolean
  53. */
  54. public function close($flag=2){
  55. switch($flag){
  56. // 关闭 Master
  57. case 0:
  58. $this->getRedis()->close();
  59. break;
  60. // 关闭 Slave
  61. case 1:
  62. for($i=0; $i_sn; ++$i){
  63. $this->_linkHandle['slave'][$i]->close();
  64. }
  65. break;
  66. // 关闭所有
  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. * 得到 Redis 原始对象可以有更多的操作
  78. *
  79. * @param boolean $isMaster 返回服务器的类型 true:返回Master false:返回Slave
  80. * @param boolean $slaveOne 返回的Slave选择 true:负载均衡随机返回一个Slave选择 false:返回所有的Slave选择
  81. * @return redis object
  82. */
  83. public function getRedis($isMaster=true,$slaveOne=true){
  84. // 只返回 Master
  85. if($isMaster){
  86. return $this->_linkHandle['master'];
  87. }else{
  88. return $slaveOne ? $this->_getSlaveRedis() : $this->_linkHandle['slave'];
  89. }
  90. }
  91. /**
  92. * 写缓存
  93. *
  94. * @param string $key 组存KEY
  95. * @param string $value 缓存值
  96. * @param int $expire 过期时间, 0:表示无过期时间
  97. */
  98. public function set($key, $value, $expire=0){
  99. // 永不超时
  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. * 读缓存
  109. *
  110. * @param string $key 缓存KEY,支持一次取多个 $key = array('key1','key2')
  111. * @return string || boolean 失败返回 false, 成功返回字符串
  112. */
  113. public function get($key){
  114. // 是否一次取多个值
  115. $func = is_array($key) ? 'mGet' : 'get';
  116. // 没有使用M/S
  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. * 条件形式设置缓存,如果 key 不存时就设置,存在时设置失败
  131. *
  132. * @param string $key 缓存KEY
  133. * @param string $value 缓存值
  134. * @return boolean
  135. */
  136. public function setnx($key, $value){
  137. return $this->getRedis()->setnx($key, $value);
  138. }
  139. /**
  140. * 删除缓存
  141. *
  142. * @param string || array $key 缓存KEY,支持单个健:"key1" 或多个健:array('key1','key2')
  143. * @return int 删除的健的数量
  144. */
  145. public function remove($key){
  146. // $key => "key1" || array('key1','key2')
  147. return $this->getRedis()->delete($key);
  148. }
  149. /**
  150. * 值加加操作,类似 ++$i ,如果 key 不存在时自动设置为 0 后进行加加操作
  151. *
  152. * @param string $key 缓存KEY
  153. * @param int $default 操作时的默认值
  154. * @return int 操作后的值
  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. * 值减减操作,类似 --$i ,如果 key 不存在时自动设置为 0 后进行减减操作
  165. *
  166. * @param string $key 缓存KEY
  167. * @param int $default 操作时的默认值
  168. * @return int 操作后的值
  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. * 添空当前数据库
  179. *
  180. * @return boolean
  181. */
  182. public function clear(){
  183. return $this->getRedis()->flushDB();
  184. }
  185. /* =================== 以下私有方法 =================== */
  186. /**
  187. * 随机 HASH 得到 Redis Slave 服务器句柄
  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. * 根据ID得到 hash 后 0~m-1 之间的值
  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


声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
高流量网站的PHP性能调整高流量网站的PHP性能调整May 14, 2025 am 12:13 AM

TheSecretTokeEpingAphp-PowerEdwebSiterUnningSmoothlyShyunderHeavyLoadInVolvOLVOLVOLDEVERSALKEYSTRATICES:1)emplactopCodeCachingWithOpcachingWithOpCacheToreCescriptexecution Time,2)使用atabasequercachingCachingCachingWithRedataBasEndataBaseLeSendataBaseLoad,3)

PHP中的依赖注入:初学者的代码示例PHP中的依赖注入:初学者的代码示例May 14, 2025 am 12:08 AM

你应该关心DependencyInjection(DI),因为它能让你的代码更清晰、更易维护。1)DI通过解耦类,使其更模块化,2)提高了测试的便捷性和代码的灵活性,3)使用DI容器可以管理复杂的依赖关系,但要注意性能影响和循环依赖问题,4)最佳实践是依赖于抽象接口,实现松散耦合。

PHP性能:是否可以优化应用程序?PHP性能:是否可以优化应用程序?May 14, 2025 am 12:04 AM

是的,优化papplicationispossibleandessential.1)empartcachingingcachingusedapcutorediucedsatabaseload.2)优化的atabaseswithexing,高效Quereteries,and ConconnectionPooling.3)EnhanceCodeWithBuilt-unctions,避免使用,避免使用ingglobalalairaiables,并避免使用

PHP性能优化:最终指南PHP性能优化:最终指南May 14, 2025 am 12:02 AM

theKeyStrategiestosiminificallyBoostphpapplicationPermenCeare:1)useOpCodeCachingLikeLikeLikeLikeLikeCacheToreDuceExecutiontime,2)优化AtabaseInteractionswithPreparedStateTemtStatementStatementSandProperIndexing,3)配置

PHP依赖注入容器:快速启动PHP依赖注入容器:快速启动May 13, 2025 am 12:11 AM

aphpdepentioncontiveContainerIsatoolThatManagesClassDeptions,增强codemodocultion,可验证性和Maintainability.itactsasaceCentralHubForeatingingIndections,因此reducingTightCightTightCoupOulplingIndeSingantInting。

PHP中的依赖注入与服务定位器PHP中的依赖注入与服务定位器May 13, 2025 am 12:10 AM

选择DependencyInjection(DI)用于大型应用,ServiceLocator适合小型项目或原型。1)DI通过构造函数注入依赖,提高代码的测试性和模块化。2)ServiceLocator通过中心注册获取服务,方便但可能导致代码耦合度增加。

PHP性能优化策略。PHP性能优化策略。May 13, 2025 am 12:06 AM

phpapplicationscanbeoptimizedForsPeedAndeffificeby:1)启用cacheInphp.ini,2)使用preparedStatatementSwithPdoforDatabasequesies,3)3)替换loopswitharray_filtaray_filteraray_maparray_mapfordataprocrocessing,4)conformentnginxasaseproxy,5)

PHP电子邮件验证:确保正确发送电子邮件PHP电子邮件验证:确保正确发送电子邮件May 13, 2025 am 12:06 AM

phpemailvalidation invoLvesthreesteps:1)格式化进行regulareXpressecthemailFormat; 2)dnsvalidationtoshethedomainhasavalidmxrecord; 3)

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

VSCode Windows 64位 下载

VSCode Windows 64位 下载

微软推出的免费、功能强大的一款IDE编辑器

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)