redis,memcache技術現在已經應用很廣泛,"PHP腳本redis類的實例源碼",我們也會用到它,就給大家分享了吧,用它可以很簡潔,方便的調用redis里的內置函數。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 | class redisDB{ private $redis ; //redis對象 /** * 初始化Redis * $config = array( * 'server' => '127.0.0.1' 服務器 * 'port' => '6379' 端口號 * ) * @param array $config */ function __construct( $config = array ()){ $this ->redis = new Redis(); $this ->redis->connect(REDIS_SERVER,REDIS_PORT); return $this ->redis; } /** * 設置值 * @param string $key KEY名稱 * @param string|array $value 獲取得到的數據 * @param int $timeOut 時間 */ public function set( $key , $value , $timeOut = 0, $type = 'json' ) { if ( $type == 'serialize' ) { $value = serialize( $value ); } else { $value = json_encode( $value ); } $retRes = $this ->redis->set( $key , $value ); if ( $timeOut > 0) $this ->redis->setTimeout( $key , $timeOut ); return $retRes ; } /** * 通過KEY獲取數據 * @param string $key KEY名稱 */ public function get( $key , $type = 'json' ) { $result = $this ->redis->get( $key ); if ( $type == 'serialize' ) { return unserialize( $result ); } else { return json_decode( $result ); } } /** * 刪除一條數據 * @param string $key KEY名稱 */ public function delete ( $key ) { return $this ->redis-> delete ( $key ); } /** * 清空數據 */ public function flushAll() { return $this ->redis->flushAll(); } /** * 數據入隊列 * @param string $key KEY名稱 * @param string|array $value 獲取得到的數據 * @param bool $right 是否從右邊開始入 */ public function push( $key , $value , $right = true) { $value = json_encode( $value ); return $right ? $this ->redis->rPush( $key , $value ) : $this ->redis->lPush( $key , $value ); } /** * 數據出隊列 * @param string $key KEY名稱 * @param bool $left 是否從左邊開始出數據 */ public function pop( $key , $left = true) { $val = $left ? $this ->redis->lPop( $key ) : $this ->redis->rPop( $key ); return json_decode( $val ); } /** * 數據自增 * @param string $key KEY名稱 */ public function increment( $key ) { return $this ->redis->incr( $key ); } /** * 數據自減 * @param string $key KEY名稱 */ public function decrement( $key ) { return $this ->redis->decr( $key ); } /** * key是否存在,存在返回ture * @param string $key KEY名稱 */ public function exists( $key ) { return $this ->redis->exists( $key ); } /** * 返回redis對象 * redis有非常多的操作方法,我們只封裝了一部分 * 拿著這個對象就可以直接調用redis自身方法 */ public function redis() { return $this ->redis; } } |
使用方法:
1 2 3 4 5 6 7 8 | include 'redis.php' ; $redis = new redisDB(); $key = 'fields' ; $value = '好腳本' ; //value可以是字符串或者數組 $redis ->set( $key , $value ); //獲取fields的值也很簡單 $fvalue = $redis ->get( 'fields' ); print_r( $fvalue ); |
用到就copy吧,簡單,實用。嘿嘿 有需要用到memcache的類,可以參考一下這個。
新聞熱點
疑難解答