PHP程序连接多个redis实例做缓存

时间:2023-02-01 21:25:09
1、redis配置:
$CONFIG_REDIS = array(
    array('host' => '192.168.19.29', 'port' => '6379', 'dbIndex' => 0, 'password'=>'3695a77369be021075b480048142a3c2'),
    array('host' => '192.168.19.30', 'port' => '6379', 'dbIndex' => 0, 'password'=>'3695a77369be021075b480048142a3c2')
);
 
2、Redis操作封装类-->UtilRedis2
class UtilRedis2 {
 
 private static $_self = null;
 private $_servers = array();
 private $_conn = array();
 private $_conn_keys = array();
 
 const CONNECT_TIMEOUT = 5;
 
 public static function &getInstance() {
  // TODO Auto-generated method stub
  if (null == self::$_self)
  {
   self::$_self = new self();
  }
  return self::$_self;
 }
 
 private function __construct() {
  $this->_servers = $GLOBALS['CONFIG_REDIS'];
 }
 
 private function getConnection( $key ) {
  
  $serverCnt = count( $this->_servers );
  $hash = md5( $key );
  $serverIndex = $hash % $serverCnt;
  
  if ( !isset( $this->_conn[ $serverIndex ] ) ) {
   $this->_conn[ $serverIndex ] = new Redis();
   $this->_conn[ $serverIndex ]->pconnect(
          $this->_servers[$serverIndex]['host'],
          $this->_servers[$serverIndex]['port'],
          self::CONNECT_TIMEOUT
          );
   $this->_conn[ $serverIndex ]->auth($this->_servers[$serverIndex]['password']);
   $this->_conn[ $serverIndex ]->select( $this->_servers[$serverIndex]['dbIndex'] );
  }
  
  return $this->_conn[ $serverIndex ];
 }
 
 public function set( $key, $value, $expires = 0 ) {
  $conn = $this->getConnection( $key );
  
  if( $conn->set( $key, $value ) && $expires > 0 )
   return $conn->setTimeout($key, $expires);
  return true;
 }
......
 
3、使用redis操作封装类
$redis = UtilRedis2::getInstance();
$redis->set("development", "wangwu");
<?php
//连接本地的 Redis 服务
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
//$redis->auth('123456');
$redis->select(0);
//EXPIRE key seconds------给key设置生存时间,当key过期时,它会被自动删除
//PEXPIRE key milliseconds------以毫秒为单位设置key的生存时间
//EXPIREAT key timestamp------命令接受的时间参数是UNIX时间戳,key存活到一个unix时间戳时间
//PERSIST key------移除给定key的生存时间,转换成一个不带生存时间,永不过期的key
//SORT key [BY pattern] [LIMIT offset count] [GET pattern [GET pattern ...]] [ASC | DESC] [ALPHA] [STORE destination]------返回或保存给定列表、集合、有序集合key中经过排序的元素    
/****************String(字符串)相关操作***************/
//SET key value------将字符串值value关联到key,会覆盖
$a = $redis->set('email1','jiang@58haha.cn');
$redis->setTimeout('email1',30);
$seconds = $redis->ttl('email1');
$redis->select(1);
$h = $redis->get('email1');
print_r($h);
浏览器无内容输出,因为set、get操作不在一个分区。