操作類就是把一些常用的一系列的數據庫或相關操作寫在一個類中,這樣調用時我們只要調用類文件,如果要執行相關操作就直接調用類文件中的方法函數就可以實現了,下面整理了一個Memcache數據緩存操作類庫文件,希望對各位會有幫助了.
PHP 數據庫緩存Memcache操作類代碼如下:
- class memcachedInit {
- private $memcache;
- /**
- * Memcache緩存-設置緩存
- * 設置緩存key,value和緩存時間
- * @param string $key KEY值
- * @param string $value 值
- * @param string $time 緩存時間
- */
- public function set_cache($key, $value, $time = 0) {
- return $this->memcache->set($key, $value, false, $time);
- }
- /**
- * Memcache緩存-獲取緩存
- * 通過KEY獲取緩存數據
- * @param string $key KEY值
- */
- public function get_cache($key) {
- return $this->memcache->get($key);
- }
- /**
- * Memcache緩存-清除一個緩存
- * 從memcache中刪除一條緩存
- * @param string $key KEY值
- */
- public function clear($key) {
- return $this->memcache->delete($key);
- }
- /**
- * Memcache緩存-清空所有緩存
- * 不建議使用該功能
- * @return
- */
- public function clear_all() {
- return $this->memcache->flush();
- }
- /**
- * 字段自增-用于記數
- * @param string $key KEY值
- * @param int $step 新增的step值
- */
- public function increment($key, $step = 1) {
- return $this->memcache->increment($key, (int) $step);
- }
- /**
- * 字段自減-用于記數
- * @param string $key KEY值
- * @param int $step 新增的step值
- */
- public function decrement($key, $step = 1) {
- return $this->memcache->decrement($key, (int) $step);
- }
- /**
- * 關閉Memcache鏈接
- */
- public function close() {
- return $this->memcache->close();
- }
- /**
- * 替換數據
- * @param string $key 期望被替換的數據
- * @param string $value 替換后的值
- * @param int $time 時間值
- * @param bool $flag 是否進行壓縮
- */
- public function replace($key, $value, $time = 0, $flag = false) {
- return $this->memcache->replace($key, $value, false, $time);
- }
- /**
- * 獲取Memcache的版本號
- */
- public function getVersion() {
- return $this->memcache->getVersion();
- }
- /**
- * 獲取Memcache的狀態數據
- */
- public function getStats() {
- return $this->memcache->getStats();
- }
- /**
- * Memcache緩存-設置鏈接服務器
- * 支持多MEMCACHE服務器
- * 配置文件中配置Memcache緩存服務器:
- * $InitPHP_conf['memcache'][0] = array('127.0.0.1', '11211');
- * @param array $servers 服務器數組-array(array('127.0.0.1', '11211'))
- */
- public function add_server($servers) {
- $this->memcache = new Memcache;
- if (!is_array($servers) || emptyempty($servers)) exit('memcache server is null!');//開源代碼Vevb.com
- foreach ($servers as $val) {
- $this->memcache->addServer($val[0], $val[1]);
- }
- }
- }
使用方法:
$newclass = new memcachedInit();
$newclass->getVersion() //獲取版本號
$newclass->close() //關閉Memcache鏈接
$newclass->clear($key) //從memcache中刪除一條緩存
$newclass->get_cache($key) //通過KEY獲取緩存數據
上面就簡單介紹了它的使用方法了,其實還有很多在這里我就不介紹了呀.
總結:這個只是一個最基于的Memcache緩存操作類了,比起像數據庫緩存類操作會更好更復雜了,希望例子能幫助到各位朋友.
新聞熱點
疑難解答