php监听
A. 订单超时,活动过期解决方案:php监听redis键重复触发引发事件
订单超时,活动过期解决方案:php监听redis键重复触发引发事件
Redis的2.8.0版本之后可用,键空间消息(Redis Keyspace Notifications),配合2.0.0版本之后的SUBSCRIBE 可以完成这个定时任务的操作了,定时的单位是秒。
1.我们先订阅频道称为 redisChat
2.现在,我们重新开启个redis客户端,然后在同一个频道redisChat发布消息,订阅者可以接收到消息。
接收到的消息如下:
3.Key过期事件的Redis配置
需要这里配置notify-keyspace-events的参数为“EX” .X代表了过期事件。notify-keyspace-events “Ex”保存配置后,重启Redis的服务,使配置生效。
PHP Redis实现订阅键空间通知
redis实例化类:
redis.class.php
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
//遇到类别重复的报错,所有叫Redis2
classRedis2
{
private$redis;
publicfunction__construct($host= '127.0.0.1', $port= 6379)
{
$this->redis = newRedis();
$this->redis->connect($host, $port);
}
publicfunctionsetex($key, $time, $val)
{
return$this->redis->setex($key, $time, $val);
}
publicfunctionset($key, $val)
{
return$this->redis->set($key, $val);
}
publicfunctionget($key)
{
return$this->redis->get($key);
}
publicfunctionexpire($key= null, $time= 0)
{
return$this->redis->expire($key, $time);
}
publicfunctionpsubscribe($patterns= array(), $callback)
{
$this->redis->psubscribe($patterns, $callback);
}
publicfunctionsetOption()
{
$this->redis->setOption(\Redis::OPT_READ_TIMEOUT, -1);
}
}
过期事件的订阅:
psubscribe.php
1个
2
3
4
5
6
7
8
9
10
11
12
13
14
15
require_once'./Redis.class.php';
$redis= new\Redis2();
// 解决Redis客户端订阅时候超时情况
$redis->setOption();
$redis->psubscribe(array('__keyevent@0__:expired'), 'keyCallback');
// 回调函数,这里写处理逻辑
functionkeyCallback($redis, $pattern, $chan, $msg)
{
echo"Pattern: $pattern\n";
echo"Channel: $chan\n";
echo"Payl
oad: $msg\n\n";
//keyCallback为订阅事件后的回调函数,这里写业务处理逻辑,
//比如前面提到的商品不支付自动撤单,这里就可以根据订单id,来实现自动撤单
}
设置过期事件:
index.php
1个
2
3
4
require_once'./Redis.class.php';
$redis= new\Redis2();
$order_id= 123;
$redis->setex('order_id',10,$order_id);
先用命令行模式执行 psubscribe.php
在浏览器访问 index.php
效果如下:
B. php 如何监听服务器端口
<?php
//设置运行时间:永不超时
set_time_limit (0);
//开启缓冲
ob_implicit_flush ();
//IP地址
$ip = "127.0.0.1";
//监听端口
$port = 80;
//创建socket
$socket = socket_create (AF_INET, SOCK_STREAM, 0);
if (!$socket){
die("创建socket失败!").socket_strerror(socket_last_error());
}
//绑定socket
$bind = socket_bind ($socket, $ip, $port);
if (!$bind){
die("绑定.socket失败!").socket_strerror ($bind);
}
//监听socket
$listen = socket_listen ($socket);
if (!$listen){
die("监听失败!").socket_strerror ($listen);
}
echo "{$port}端口监听成功!";
?>
C. PHP服务端监听UDP通信方式
例子代码:
<?php
$sock=socket_create(AF_INET,SOCK_DGRAM,SOL_UDP);
$msg="Ping!";
$len=strlen($msg);
socket_sendto($sock,$msg,$len,0,'127.0.0.1',1223);
socket_close($sock);
?>
查看手册中相关的函数就知道进一步应该怎么编程。
D. php中有没有什么方法可以实现实时监听数据库中的某张表的变化
最好的办法是,在应用程序生命周期内,对于数据库设置有事件钩子,用于监听程序对于数据库的操作。这样非常方便处理逻辑流程。
1 - 表的数据变化
表数据发生了变化,毫无疑问是写操作,包括以下几种情形:
新建条目 create
更新条目 update
删除条目 delete
以上三种都是写操作,会对表数据写入。
Laravel Observer
结语
上面的方法要求读者有laravel框架的使用基础,对于构建中大型应用非常有利。