這篇文章主要介紹了php實(shí)現(xiàn)redis數(shù)據(jù)庫(kù)指定庫(kù)號(hào)遷移的方法,涉及對(duì)于redis數(shù)據(jù)庫(kù)的操作技巧,非常具有實(shí)用價(jià)值,需要的朋友可以參考下
創(chuàng)新互聯(lián)建站長(zhǎng)期為成百上千客戶提供的網(wǎng)站建設(shè)服務(wù),團(tuán)隊(duì)從業(yè)經(jīng)驗(yàn)10年,關(guān)注不同地域、不同群體,并針對(duì)不同對(duì)象提供差異化的產(chǎn)品和服務(wù);打造開放共贏平臺(tái),與合作伙伴共同營(yíng)造健康的互聯(lián)網(wǎng)生態(tài)環(huán)境。為碾子山企業(yè)提供專業(yè)的做網(wǎng)站、網(wǎng)站建設(shè),碾子山網(wǎng)站改版等技術(shù)服務(wù)。擁有10多年豐富建站經(jīng)驗(yàn)和眾多成功案例,為您定制開發(fā)。
本文實(shí)例講述了php實(shí)現(xiàn)redis數(shù)據(jù)庫(kù)指定庫(kù)號(hào)遷移的方法,分享給大家供大家參考。具體如下:
redis普通的數(shù)據(jù)庫(kù)遷移,只能整個(gè)redis
save,或者利用主從,當(dāng)然也可以安裝一個(gè)redis-dump,不過(guò)比較麻煩,這里提供一種php的腳本,實(shí)現(xiàn)指定庫(kù)號(hào)的遷移,其實(shí)也就是遍歷根據(jù)存儲(chǔ)類型,讀出來(lái),插入新庫(kù),效果是這樣:
代碼如下:
[root@localhost
~]#
php
1.php
1/407
101/407
201/407
301/407
401/407
PHP實(shí)例代碼如下:
代碼如下:
?php
$from
=
'10.0.2.52:6379/7';
$to
=
'127.0.0.1:6379/7';
$from_redis
=
redis_init($from);
$to_redis
=
redis_init($to);
$keys
=
$from_redis-keys('*');
$count
=
0;
$total
=
count($keys);
foreach($keys
as
$key){
if(++$count
%
100
==
1){
echo
"$count/$totaln";
}
$type
=
$from_redis-type($key);
switch($type){
case
Redis::REDIS_STRING:
$val
=
$from_redis-get($key);
$to_redis-set($key,
$val);
break;
case
Redis::REDIS_LIST:
$list
=
$from_redis-lRange($key,
0,
-1);
foreach($list
as
$val){
$to_redis-rPush($key,
$val);
}
break;
case
Redis::REDIS_HASH:
$hash
=
$from_redis-hGetAll($key);
$to_redis-hMSet($key,
$hash);
break;
case
Redis::REDIS_ZSET:
$zset
=
$from_redis-zRange($key,
0,
-1,
true);
foreach($zset
as
$val=$score){
$to_redis-zAdd($key,
$score,
$val);
}
break;
}
}
function
redis_init($conf){
$redis
=
new
Redis();
preg_match('/^([^:]+)(:[0-9]+)?/(.+)?/',
$conf,
$ms);
$host
=
$ms[1];
$port
=
trim($ms[2],
':');
$db
=
$ms[3];
$redis-connect($host,
$port);
$redis-select($db);
return
$redis;
}
?
希望本文所述對(duì)大家的php程序設(shè)計(jì)有所幫助。
redis是一個(gè)key-value存儲(chǔ)系統(tǒng)。和Memcached類似,它支持存儲(chǔ)的value類型相對(duì)更多,包括string(字符串)、list(鏈表)、set(集合)和zset(有序集合)。這些數(shù)據(jù)類型都支持push/pop、add/remove及取交集并集和差集及更豐富的操作,而且這些操作都是原子性的。在此基礎(chǔ)上,redis支持各種不同方式的排序。與memcached一樣,為了保證效率,數(shù)據(jù)都是緩存在內(nèi)存中。區(qū)別的是redis會(huì)周期性的把更新的數(shù)據(jù)寫入磁盤或者把修改操作寫入追加的記錄文件,并且在此基礎(chǔ)上實(shí)現(xiàn)了master-slave(主從)同步。
Redis 是一個(gè)高性能的key-value數(shù)據(jù)庫(kù)。redis的出現(xiàn),很大程度補(bǔ)償了memcached這類keyvalue存儲(chǔ)的不足,在部 分場(chǎng)合可以對(duì)關(guān)系數(shù)據(jù)庫(kù)起到很好的補(bǔ)充作用。它提供了Python,Ruby,Erlang,PHP客戶端,使用很方便。
若想在PHP中使用redis,首先要先安裝redis。然后在PHP中配置擴(kuò)展。
安裝redis。
首先下載好redis安裝文件,解壓到D盤或其他盤。
然后通過(guò)Dos命令行進(jìn)行安裝。
把這個(gè)文件夾復(fù)制到其它地方,比如D:\redis 目錄下。
打開一個(gè)cmd窗口 使用cd命令切換目錄到D:\redis 運(yùn)行 redis-server.exe redis.conf
如果想方便的話,可以把redis的路徑加到系統(tǒng)的環(huán)境變量里,這樣就省得再輸路徑了,后面的那個(gè)redis.conf可以省略,如果省略,會(huì)啟用默認(rèn)的。
這時(shí)候另啟一個(gè)cmd窗口,原來(lái)的不要關(guān)閉,不然就無(wú)法訪問(wèn)服務(wù)端了
切換到redis目錄下運(yùn)行 redis-cli.exe -h 127.0.0.1 -p 6379
這時(shí)候,就已經(jīng)完成配置了。
完成了配置之后,要在PHP中添加redis的擴(kuò)展,之后才可以用PHP靈活的使用它。
在windows下安裝php的redis擴(kuò)展非常簡(jiǎn)單,下載一個(gè).dll擴(kuò)展包放到php的ext目錄下,在php.ini里邊添加一行配置就可以了。
php代碼測(cè)試
redis=newRedis();redis-connect(‘127.0.0.1′,6379);
redis?set(‘test′,′helloworld!′);echoredis-get(‘test’);
輸出hello world!
?php
/**
* Redis緩存操作
* @author hxm
* @version 1.0
* @since 2015.05.04
*/
class RCache extends Object implements CacheFace
{
private $redis = null; //redis對(duì)象
private $sId = 1; //servier服務(wù)ID
private $con = null;//鏈接資源
/**
* 初始化Redis
*
* @return Object
*/
public function __construct()
{
if ( !class_exists('Redis') )
{
throw new QException('PHP extension does not exist: Redis');
}
$this-redis = new Redis();
}
/**
* 鏈接memcahce服務(wù)
*
* @access private
* @param string $key 關(guān)鍵字
* @param string $value 緩存內(nèi)容
* @return array
*/
private function connect( $sid )
{
$file = $this-CacheFile();
require $file;
if(! isset($cache) )
{
throw new QException('緩存配置文件不存在'.$file);
}
$server = $cache[$this-cacheId];
$sid = isset($sid) == 0 ? $this-sId : $sid;//memcache服務(wù)選擇
if ( ! $server[$sid])
{
throw new QException('當(dāng)前操作的緩存服務(wù)器配置文件不存在');
}希望能幫到你,我還在后盾網(wǎng)學(xué)習(xí)呢,有不會(huì)的可以問(wèn)我,一會(huì)有空回答你。( ^ω^)
存儲(chǔ)普通數(shù)據(jù)就用set,讀取就用get。存儲(chǔ)普通數(shù)據(jù)就用set,讀取就用get。
但是存儲(chǔ)之前最好是先判斷一下。
下面是一段相關(guān)的代碼。
?php
$redis?=?new?Redis();
$redis-connect('127.0.0.1',?6379);//連接redis
if?(!$redis-exists("content")){
//如果沒(méi)有content這個(gè)key,就新建一個(gè),并存儲(chǔ)數(shù)據(jù)。
$redis-set("content",$content);
}else{
//如果存在,則讀取content這個(gè)key里面的數(shù)據(jù)
echo?$redis-get("content");
}
?
推薦去三體教程看看,有redis存儲(chǔ)讀取數(shù)據(jù)方法的詳解。
對(duì)于大訪問(wèn)量的站點(diǎn)使用默認(rèn)的Session 并不合適,我們可以將其存入數(shù)據(jù)庫(kù)、或者使用Redis KEY-VALUE數(shù)據(jù)存儲(chǔ)方案
首先新建一個(gè)session表
CREATE TABLE `sessions` (
`sid` char(40) NOT NULL,
`updatetime` int(20) NOT NULL,
`data` varchar(200) NOT NULL,
UNIQUE KEY `sid` (`sid`) USING HASH
) ENGINE=MEMORY DEFAULT CHARSET=utf8;
Mysql 的memory引擎采用內(nèi)存表,所有數(shù)據(jù)存儲(chǔ)在內(nèi)存,操作速度快
復(fù)制代碼
?php
//引入數(shù)據(jù)庫(kù)文件
include "db.php";
class MySessionHandler implements SessionHandlerInterface
{
private $savePath;
private $sessData;
public $expiretime; //設(shè)置過(guò)期時(shí)間
public $db; //數(shù)據(jù)庫(kù)
public function __construct($hanlder =''){
$this-db = Database::getInstance();
//獲取數(shù)據(jù)庫(kù)實(shí)力
///var_dump($this-db);
}
public function open($savePath, $sessionName)
{
return true;
}
public function close()
{
return true;
}
public function read($id)
{
$sql ="select * from sessions where sid ='$id'";
$result = $this-db-execute($sql);
if(!empty($result)){
return $this-sessData = $result;
}
}
//函數(shù)的參數(shù) $id - 當(dāng)前會(huì)話ID
//數(shù)據(jù)DATA - 序列化之后的字符串
public function write($id, $data)
{
// echo $id;
// echo $data;
$now = time();
$newExp = $now+$this-expiretime; //總時(shí)間=當(dāng)前時(shí)間 + 期限時(shí)間
$sql = "select * from sessions where sid ='$id'";
$result = $this-db-getOne($sql);
//var_dump($result);
if($data==''||isset($data)){
$data = $this-sessData;
}
if($result){
//如果存在則更新
$sql ="update sessions set updatetime = '$newExp',data ='$data' where sid = '$id'";
//echo $sql;
$update_data =$this-db-execute($sql);
if($update_data){
return true;
}
}else{
//不存在則生成生成
$sql = "insert into sessions(sid,updatetime,data) values('$id','$now','$data')";
$insert_data = $this-db-execute($sql);
if($insert_data){
return true;
}
}
return false;
}
public function destroy($id)
{ //銷毀
$sql = "delete from sessions where sid="."$id";
$destory = $this-db-execute($sql);
if($destory){
return true;
}else{
return false;
}
}
public function gc($sessMaxLifeTime)
{
$t = time();
$sql ="delete from sessions where $t - 'updatetime'${sessMaxLifeTime}";
$data = $this-db-execute($this-tosql);
if($data){
return true;
}else{
return false;
}
return true;
}
}
復(fù)制代碼
實(shí)例化
此處 PHP 手冊(cè)可以有兩種方法
1,實(shí)現(xiàn)了SessionHandlerInterface借口的對(duì)象,自PHP5.4可以使用
2 ,直接使用 session_set_save_handler
復(fù)制代碼
//判斷PHP版本
if(version_compare(PHP_VERSION,5.4)==1){
session_set_save_handler($handler, true);
session_start();
}else{
ini_set('session.use_trans_sid',0);
ini_set('session.use_cookies',1);
ini_set('session.cookie_path','/');
ini_set('session.save_handler','user');
session_module_name('user');
session_set_save_handler(array($session,"open"),array($session,"close"),array($session,"read"),array($session,"write"),array($session,"destory"),array($session,"gc"));
session_start();
}
$_SESSION['QQ']="QQ";
echo $_SESSION['QQ'];
復(fù)制代碼
數(shù)據(jù)庫(kù)代碼 db.php
復(fù)制代碼
?php
class Database{
static $instance;
static $db;
static function getInstance(){
if(self::$instance){
return self::$instance;
}else{
return new Database();
}
}
public function __construct(){
self::$db = new PDO('mysql:host=localhost;dbname=session', 'root','');
}
public function getOne($sql){
$rs =self::$db-query($sql);
@$rs-setFetchMode(PDO::FETCH_ASSOC);//返回關(guān)聯(lián)數(shù)組
$result = $rs - fetch();
return $result;
}
public function execute($sql){
$rs = self::$db-exec($sql);
return $rs;
}
}
//$data = Database::getInstance();
//var_dump($data);
復(fù)制代碼
使用REDIS 存儲(chǔ)SESSION
復(fù)制代碼
?php
class SessionManager{
private $redis;
private $sessionSavePath;
private $sessionName;
private $sessionExpireTime = 30;
public function __construct(){
$this-redis = new Redis();
$this-redis-connect('127.0.0.1',6379); //連接redis
$retval = session_set_save_handler(
array($this,"open"),
array($this,"close"),
array($this,"read"),
array($this,"write"),
array($this,"destory"),
array($this,"gc")
);
session_start();
}
public function open($path,$name){
return true;
}
public function close(){
return true;
}
public function read($id){
$value = $this-redis-get($id);
if($value){
return $value;
}else{
return "";
}
}
public function write($id,$data){
if($this-redis-set($id,$data)){
$this-redis-expire($id,$this-sessionExpireTime);
//設(shè)置過(guò)期時(shí)間
return true;
}
return false;
}
public function destory($id){
if($this-redis-delete($id)){
return true;
}
return false;
}
public function gc($maxlifetime){
return true;
}
//析構(gòu)函數(shù)
public function __destruct(){
session_write_close();
}
}
$re = new SessionManager();
$_SESSION['name'] = "qq";
echo $_SESSION['name'];
select 查詢的時(shí)候始終先查 redis 有沒(méi)有,沒(méi)有去查數(shù)據(jù)庫(kù),再把結(jié)果緩存起來(lái);
update 修改完數(shù)據(jù)庫(kù)內(nèi)容后,同時(shí)對(duì) redis 中緩存的數(shù)據(jù)做一下 update 更新操作,這樣 select 查詢 redis 的時(shí)候就是查詢的最新數(shù)據(jù);
同理,delete、insert 操作數(shù)據(jù)庫(kù)后也要同時(shí)對(duì) redis 中緩存的數(shù)據(jù)做 update 更新操作,這樣 select 查詢 redis 的時(shí)候就是查詢的最新數(shù)據(jù);
這樣,所有的查詢操作就都是對(duì) redis 做緩存讀取,可以緩解數(shù)據(jù)庫(kù)的壓力;
分享標(biāo)題:php寫數(shù)據(jù)redis php寫數(shù)據(jù)庫(kù)接口
鏈接地址:http://chinadenli.net/article12/dodsjdc.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供全網(wǎng)營(yíng)銷推廣、品牌網(wǎng)站設(shè)計(jì)、虛擬主機(jī)、品牌網(wǎng)站制作、域名注冊(cè)、關(guān)鍵詞優(yōu)化
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)