1. 程式人生 > >PHP程序連接多個redis實例做緩存

PHP程序連接多個redis實例做緩存

unix時間戳 auto 配置 相關操作 store $_server fun 自動刪除 method

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‘,‘[email protected]‘);
$redis->setTimeout(‘email1‘,30);
$seconds = $redis->ttl(‘email1‘);
$redis->select(1);
$h = $redis->get(‘email1‘);
print_r($h);

瀏覽器無內容輸出,因為set、get操作不在一個分區。

PHP程序連接多個redis實例做緩存