Redis是一種常用的非關系型數據庫,主要用作數據緩存,數據保存形式為key-value,鍵值相互映射.它的數據存儲跟MySQL不同,它數據存儲在內存之中,所以數據讀取相對而言很快,用來做高並發非常不錯.
ThinkPhP5.0自帶了Redis擴展,在使用之前先下載php_redis.dll 網址 http://windows.php.net/downloads/pecl/releases/redis/2.2.7/ ;根據自己windows操作系統選擇相應的版本,我自己是系統64位,安裝的是VC2012 所以下載的是php_redis-2.2.7-5.6-ts-vc11-x64.zip
下載好壓縮包之后,把里面的php_redis.dll 解壓到D:\wamp\bin\php\php5.6.25\ext (根據自己wamp所在的盤自己選擇),然后在php.ini里面添加extension=php_redis.dll,重新啟動apache就可以了 //linxu下安裝phpredis擴展還要重啟service php-fpm reload;
下面是我自己測試的代碼,可以使用,封裝的不多,可以根據自己的需求去動手封裝
extend 是thinkPHP5.0的擴展類庫目錄,可以自己去定義
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
|
namespace
My;
//目錄我放在thinkphp5.0/extend/My
class
RedisPackage
{
protected
static
$handler
= null;
protected
$options
= [
'host'
=>
'127.0.0.1'
,
'port'
=> 6379,
'password'
=>
''
,
'select'
=> 0,
'timeout'
=> 0,
//關閉時間 0:代表不關閉
'expire'
=> 0,
'persistent'
=> false,
'prefix'
=>
''
,
];
public
function
__construct(
$options
= [])
{
if
(!
extension_loaded
(
'redis'
)) {
//判斷是否有擴展(如果你的apache沒reids擴展就會拋出這個異常)
throw
new
\BadFunctionCallException(
'not support: redis'
);
}
if
(!
empty
(
$options
)) {
$this
->options =
array_merge
(
$this
->options,
$options
);
}
$func
=
$this
->options[
'persistent'
] ?
'pconnect'
:
'connect'
;
//判斷是否長連接
self::
$handler
=
new
\Redis;
self::
$handler
->
$func
(
$this
->options[
'host'
],
$this
->options[
'port'
],
$this
->options[
'timeout'
]);
if
(
''
!=
$this
->options[
'password'
]) {
self::
$handler
->auth(
$this
->options[
'password'
]);
}
if
(0 !=
$this
->options[
'select'
]) {
self::
$handler
->select(
$this
->options[
'select'
]);
}
}
/**
* 寫入緩存
* @param string $key 鍵名
* @param string $value 鍵值
* @param int $exprie 過期時間 0:永不過期
* @return bool
*/
public
static
function
set(
$key
,
$value
,
$exprie
= 0)
{
if
(
$exprie
== 0) {
$set
= self::
$handler
->set(
$key
,
$value
);
}
else
{
$set
= self::
$handler
->setex(
$key
,
$exprie
,
$value
);
}
return
$set
;
}
/**
* 讀取緩存
* @param string $key 鍵值
* @return mixed
*/
public
static
function
get(
$key
)
{
$fun
=
is_array
(
$key
) ?
'Mget'
:
'get'
;
return
self::
$handler
->{
$fun
}(
$key
);
}
/**
* 獲取值長度
* @param string $key
* @return int
*/
public
static
function
lLen(
$key
)
{
return
self::
$handler
->lLen(
$key
);
}
/**
* 將一個或多個值插入到列表頭部
* @param $key
* @param $value
* @return int
*/
public
static
function
LPush(
$key
,
$value
,
$value2
= null,
$valueN
= null)
{
return
self::
$handler
->lPush(
$key
,
$value
,
$value2
,
$valueN
);
}
/**
* 移出並獲取列表的第一個元素
* @param string $key
* @return string
*/
public
static
function
lPop(
$key
)
{
return
self::
$handler
->lPop(
$key
);
}
}
|