Redis 几种应用场景
字符串缓存
<?php
$redis =
new Redis();
$redis->connect(
'127.0.0.1',
6379);
$strKey =
'test';
$strKey1 =
'test1';
$arrCache = [
'name'=>
'mysteryH',
'sex'=>
'男',
'age'=>
22
];
$redis->set(
$strKey,json_encode(
$arrCache));
$redis->expire(
$strKey,
300);
$json_data =
$redis->get(
$strKey);
$data = json_decode(
$json_data);
print_r(
$data->name);
$arrWeb =[
'google'=>[
'google.com',
'google.com.hk'
]
];
$redis->hSet(
$strKey1,
'google',json_encode(
$arrWeb[
'google']));
$json_data =
$redis->hGet(
$strKey1,
'google');
$data = json_decode(
$json_data);
print_r(
$data);
简单消息队列
<?php
$redis =
new Redis();
$redis->connect(
'127.0.0.1',
6379);
$strKey =
'queue';
$redis->rPush(
$strKey,json_encode([
'id'=>
1,
'name'=>
'name1']));
$redis->rPush(
$strKey,json_encode([
'id'=>
2,
'name'=>
'name2']));
$redis->rPush(
$strKey,json_encode([
'id'=>
3,
'name'=>
'name3']));
$redis->rPush(
$strKey,json_encode([
'id'=>
4,
'name'=>
'name4']));
echo "---进队成功---<br>";
$strCount =
$redis->lRange(
$strKey,
0,-
1);
echo "当前数据:";
print_r(
$strCount);
$info =
$redis->lPop(
$strKey);
echo "<br>---".
$info.
"---出队成功<br>";
$strCount =
$redis->lRange(
$strKey,
0,-
1);
echo "当前数据:";
print_r(
$strCount);
发布订阅
发布:
<?php
ini_set(
'default_socket_timeout',-
1);
$redis =
new Redis();
$redis->connect(
'127.0.0.1',
6379);
$strChannel =
'channel';
$redis->publish(
$strChannel,
"来自{$strChannel}的推送");
echo "-------{$strChannel}-------消息推送成功";
订阅:
<?php
ini_set(
'default_socket_timeout',-
1);
$redis =
new Redis();
$redis->connect(
'127.0.0.1',
6379);
$strChannel =
'channel';
echo "等待-------{$strChannel}-------消息推送";
$redis->subscribe([
$strChannel],
'callback');
function callback($instance, $channelName, $message){
echo $message;
}
排行榜
<?php
$redis =
new Redis();
$redis->connect(
'127.0.0.1',
6379);
$strKey =
'rank';
$redis->zAdd(
$strKey,
'50',json_encode([
'name'=>
'name1']));
$redis->zAdd(
$strKey,
'100',json_encode([
'name'=>
'name2']));
$redis->zAdd(
$strKey,
'20',json_encode([
'name'=>
'name3']));
$redis->zAdd(
$strKey,
'60',json_encode([
'name'=>
'name4']));
$redis->zAdd(
$strKey,
'40',json_encode([
'name'=>
'name5']));
$redis->zAdd(
$strKey,
'80',json_encode([
'name'=>
'name6']));
$data1 =
$redis->zRevRange(
$strKey,
0,-
1,
true);
echo "从大到小排序:<br>";
print_r(
$data1);
$data2 =
$redis->zRange(
$strKey,
0,-
1,
true);
echo "从小到大排序:<br>";
print_r(
$data2);
转载请注明原文地址: https://www.6miu.com/read-11069.html