php串連redis的應用執行個體

來源:互聯網
上載者:User


對於大型網站來說,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版本的擴充即可。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.