對於大型網站來說,redis是非常受歡迎的,運用redis緩衝之後,網站瞬間可以提速n倍。那麼php如何串連redis呢,下面是一個入門的範例代碼。
<?php
$redis = new Redis(); //建立一個對象
$redis->connect('127.0.0.1',6379); //串連redis
$redis->select(0); //選擇資料庫(預設16個資料庫,0-15,這個值可以在設定檔修改。)
$redis->set('a1', 'www.daixiaorui.com'); //往redis寫入一條記錄
echo $redis->get('a1'); //從redis中讀取一條記錄
?>
Redis的PHP字串執行個體
<?php
//Connecting to Redis server on localhost
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
echo "Connection to server sucessfully";
//set the data in redis string
$redis->set("tutorial-name", "Redis tutorial");
// Get the stored data and print it
echo "Stored string in redis:: " + jedis.get("tutorial-name");
?>
當執行程式時,會產生下面的結果:
Connection to server sucessfully
Stored string in redis:: Redis tutorial
Redis的PHP列表示例
<?php
//Connecting to Redis server on localhost
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
echo "Connection to server sucessfully";
//store data in redis list
$redis->lpush("tutorial-list", "Redis");
$redis->lpush("tutorial-list", "Mongodb");
$redis->lpush("tutorial-list", "Mysql");
// Get the stored data and print it
$arList = $redis->lrange("tutorial-list", 0 ,5);
echo "Stored string in redis:: "
print_r($arList);
?>
當執行程式時,會產生下面的結果:
Connection to server sucessfully
Stored string in redis::
Redis
Mongodb
Mysql
Redis的PHP鍵例
<?php
//Connecting to Redis server on localhost
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
echo "Connection to server sucessfully";
// Get the stored keys and print it
$arList = $redis->keys("*");
echo "Stored keys in redis:: "
print_r($arList);
?>
當執行程式時,會產生下面的結果:
Connection to server sucessfully
Stored string in redis::
tutorial-name
tutorial-list
就是這麼簡單,感覺有點像串連mysql資料庫一樣。運行以上代碼前,請確認您的電腦是否已安裝並啟動redis服務;請確認php已安裝redis擴充,這個具體請在phpinfo查看。如果沒有安裝,去官網下一個對應php版本的擴充即可。