函数超时return_PHP如何实现处理过期或者超时订单的,并还原库存

3527c08ab4019f4fb9656696579d475f.gif

文章来自:php自学中心网站
链接:http://www.startphp.cn/front/php/122378.html
作者:磊丰

商务合作:请加微信(QQ):2230304070

3bb19fea0d12022cc04cb519ce237fe3.png

视频教程

9cafc0af5b5605d1ee245b9e24f395bc.png

码农网每天更新3个教程:http://www.mano100.cn    158RMB升级永久会员,即可查看网站全部视频教程。有问题请咨询微信:2230304070    3354cb924d15cc0fd7e93bfc6e94c660.png3354cb924d15cc0fd7e93bfc6e94c660.png3354cb924d15cc0fd7e93bfc6e94c660.png

49aa1c6bdff6d0f29ac0afbb2e706dca.gif

3bb19fea0d12022cc04cb519ce237fe3.png

文章正文

9cafc0af5b5605d1ee245b9e24f395bc.png

订单是我们在日常开发中经常会遇到的一个功能,最近在做一个订单过期与超时的开发。订单过期与超时就不用我解释了吧,其实两者都是同一个问题来着,就是订单未支付的处理,我们要做的是对这些未支付的订单到了一定时间就自动取消,好了,你第一反应那肯定就是做一个定时任务了!是的,就是定时任务,但是哪个才会是最佳方案呢,下面来看看:

一、前端到时间请求取消

你肯定不会想着在前端来做定时请求取消该订单的,因为如果客户禁用了该应用或者没联网,那到了一定时间时,还一直都是未处理状态的。所以前端一般都是手动去触发取消订单的。

二、服务端定时查询有没有需要取消的订单,然后批量处理。

这种方法我们用得最多的,不过存在准确度的问题,还有需要确认定时任务的周期,但是我们可以结合redis来实现,我们可以在存redis时候顺便存在mysql这样的数据库做长久存储然后用服务端定时查询,这里我用到了redis的订阅功能。

首先先修改一下配置

vim /etc/redis/redis.conf
notify-keyspace-events “Ex” #x 代表了过期事件。

然后再重启redis

service redis restart

这里创建4个文件

82f2668d4584c0aefd66d93bc2192523.png

index.php  创建订单,发布消息,10s后查询订单状态并更新订单

<?php require_once 'Redis2.class.php';require_once 'db.class.php';
$redis2     = new \Redis2();
$list       = $redis2->lRange('order',0,9999999);
$mysql      = new \mysql();
$mysql->connect();
$data       = ['ordersn'=>'SN'.time().'T'.rand(10000000,99999999),'status'=>0,'createtime'=>date('Y-m-d H:i:s',time())];
$mysql->insert('order',$data);
$order_sn   = $data['ordersn'];
$redis2->setex($order_sn,10,$order_sn);

psubscribe.php,发布redis订阅的一些逻辑处理

<?php 
ini_set('default_socket_timeout', -1);  //设置不超时require_once './Redis.class.php';require_once './db.class.php';
$redis = new \Redis2();// 解决Redis客户端订阅时候超时情况
$redis->setOption();
$redis->psubscribe(array('__keyevent@0__:expired'), 'keyCallback');// 回调函数,这里写处理逻辑function keyCallback($redis, $pattern, $chan, $msg){
    $mysql = new \mysql();
    $mysql->connect();
    $where = "ordersn = '".$msg."'";
    $mysql->select('order','',$where);
    $finds=$mysql->fetchAll();if(isset($finds[0]['status']) && $finds[0]['status']==0){
        $data   = array('status' => 3,'updatetime'=>date('Y-m-d H:i:s',time()));
        $where  = "id = ".$finds[0]['id'];
        $mysql->update('order',$data,$where);
    }
}

这里我把redis的一些操作和mysql的一些处理做了封装处理,这个你们可以用到你们自己的项目当中的

Redis2.class.php

<?php class Redis2{private $redis;public function __construct($host = '127.0.0.1', $port = 6379){$this->redis = new Redis();$this->redis->connect($host, $port);$this->redis->auth('123456');
    }public function setex($key, $time, $val){return $this->redis->setex($key, $time, $val);
    }public function set($key, $val){return $this->redis->set($key, $val);
    }public function get($key){return $this->redis->get($key);
    }public function expire($key = null, $time = 0){return $this->redis->expire($key, $time);
    }public function psubscribe($patterns = array(), $callback){$this->redis->psubscribe($patterns, $callback);
    }public function setOption(){$this->redis->setOption(\Redis::OPT_READ_TIMEOUT, -1);
    }public function lRange($key,$start,$end){return $this->redis->lRange($key,$start,$end);
    }public function lPush($key, $value1, $value2 = null, $valueN = null ){return $this->redis->lPush($key, $value1, $value2 = null, $valueN = null );
    }public function delete($key1, $key2 = null, $key3 = null){return $this->redis->delete($key1, $key2 = null, $key3 = null);
    }
}

db.class.php,对sql处理的一些封装

<?php class mysql{private $mysqli;private $result;/**
     * 数据库连接
     * @param $config 配置数组
     */public function connect(){
        $config=array('host'=>'127.0.0.1','username'=>'root','password'=>'123456qwerty','database'=>'marhal','port'=>3306,
            );
        $host = $config['host'];    //主机地址
        $username = $config['username'];//用户名
        $password = $config['password'];//密码
        $database = $config['database'];//数据库
        $port = $config['port'];    //端口号$this->mysqli = new mysqli($host, $username, $password, $database, $port);
    }/**
     * 数据查询
     * @param $table 数据表
     * @param null $field 字段
     * @param null $where 条件
     * @return mixed 查询结果数目
     */public function select($table, $field = null, $where = null){
        $sql = "SELECT * FROM `{$table}`";//echo $sql;exit;if (!empty($field)) {
            $field = '`' . implode('`,`', $field) . '`';
            $sql = str_replace('*', $field, $sql);
        }if (!empty($where)) {
            $sql = $sql . ' WHERE ' . $where;
        }$this->result = $this->mysqli->query($sql);return $this->result;
    }/**
     * @return mixed 获取全部结果
     */public function fetchAll(){return $this->result->fetch_all(MYSQLI_ASSOC);
    }/**
     * 插入数据
     * @param $table 数据表
     * @param $data 数据数组
     * @return mixed 插入ID
     */public function insert($table, $data){foreach ($data as $key => $value) {
            $data[$key] = $this->mysqli->real_escape_string($value);
        }
        $keys = '`' . implode('`,`', array_keys($data)) . '`';
        $values = '\'' . implode("','", array_values($data)) . '\'';
        $sql = "INSERT INTO `{$table}`( {$keys} )VALUES( {$values} )";$this->mysqli->query($sql);return $this->mysqli->insert_id;
    }/**
     * 更新数据
     * @param $table 数据表
     * @param $data 数据数组
     * @param $where 过滤条件
     * @return mixed 受影响记录
     */public function update($table, $data, $where){foreach ($data as $key => $value) {
            $data[$key] = $this->mysqli->real_escape_string($value);
        }
        $sets = array();foreach ($data as $key => $value) {
            $kstr = '`' . $key . '`';
            $vstr = '\'' . $value . '\'';
            array_push($sets, $kstr . '=' . $vstr);
        }
        $kav = implode(',', $sets);
        $sql = "UPDATE `{$table}` SET {$kav} WHERE {$where}";$this->mysqli->query($sql);return $this->mysqli->affected_rows;
    }/**
     * 删除数据
     * @param $table 数据表
     * @param $where 过滤条件
     * @return mixed 受影响记录
     */public function delete($table, $where){
        $sql = "DELETE FROM `{$table}` WHERE {$where}";$this->mysqli->query($sql);return $this->mysqli->affected_rows;
    }
}

对每一次订单的访问我们做了服务器监听任务,如下:

cd /var/www/html/redis
#即时监听,ctrl+c 退出监听  ctrl+z 暂停监听
nohup php psubscribe.php

#后台监听
nohup php psubscribe.php &

设置本地域名并访问http://www.startphp.cn/index.php

此时,每访问一次index.php,就会创建一个订单,10s钟后,如果该订单依旧处于未支付状态,就设置订单失效。

这里要注意一下:
在命令之前加上 nohup ,启动的进程将会忽略linux的挂起信号 (SIGHUP)
这时候,当我们组合 nohup 和 &两种方式时,启动的进程不会占用控制台,并且不依赖控制台,控制台关闭之后,进程被1号进程收养,成为孤儿进程,这就和守护进程的机制非常类似了,并且nohup默认会把程序的输出重定向到当前目录下的nohup.out文件,如果没有可写权限,则写入 $homepath/nohup.out

但是php的cli模式在服务器运行后,总是会掉线,处理这个问题的方法,我们不妨写一个脚本

1.编写shell脚本,定时检查进程是否存在,不存在的话就开启服务,并且将运行情况写入日志

cd /
mkdir mytask
cd mytask
touch phprunning.sh
vi phprunning.sh

脚本文件如下:

#!/bin/sh
PIDS=`pidof php`
if [ "$PIDS" != "" ]; then
echo "在运行"
echo -e $(date +%Y"."%m"."%d" "%k":"%M":"%S)" running....." >> /mytask/task.run.log
else
echo "不在运行,开始启动"
echo -e $(date +%Y"."%m"."%d" "%k":"%M":"%S)" start php start....." >> /mytask/task.start.log
cd /var/www/html/redis
php psubscribe.php &
echo -e $(date +%Y"."%m"."%d" "%k":"%M":"%S)" start php success....." >> /mytask/task.start.log
fi

在crontab任务里创建任务,这里设定的是每5s检查一次,crontab -e

* * * * * sleep 5; sh /mytask/phprunning.sh >> /mytask/crontab.log
* * * * * sleep 10; sh /mytask/phprunning.sh >> /mytask/crontab.log
* * * * * sleep 15; sh /mytask/phprunning.sh >> /mytask/crontab.log
* * * * * sleep 20; sh /mytask/phprunning.sh >> /mytask/crontab.log
* * * * * sleep 25; sh /mytask/phprunning.sh >> /mytask/crontab.log
* * * * * sleep 30; sh /mytask/phprunning.sh >> /mytask/crontab.log
* * * * * sleep 35; sh /mytask/phprunning.sh >> /mytask/crontab.log
* * * * * sleep 40; sh /mytask/phprunning.sh >> /mytask/crontab.log
* * * * * sleep 45; sh /mytask/phprunning.sh >> /mytask/crontab.log
* * * * * sleep 50; sh /mytask/phprunning.sh >> /mytask/crontab.log
* * * * * sleep 55; sh /mytask/phprunning.sh >> /mytask/crontab.log

效果你可以查看task.run.log

cat /mytask/task.run.log

结果如下:

-e 2019.10.22 14:28:41 running.....
-e 2019.10.22 14:28:46 running.....
-e 2019.10.22 14:28:51 running.....
-e 2019.10.22 14:28:56 running.....
-e 2019.10.22 14:29:06 running.....
-e 2019.10.22 14:29:11 running.....
-e 2019.10.22 14:29:16 running.....
-e 2019.10.22 14:29:21 running.....
-e 2019.10.22 14:29:26 running.....
-e 2019.10.22 14:29:31 running.....
-e 2019.10.22 14:29:36 running.....
-e 2019.10.22 14:29:41 running.....
-e 2019.10.22 14:29:46 running.....

以上是本文的全部内容,希望对大家的学习有帮助,也希望大家多多支持 php自学中心 感谢阅读!

5ffbdf598f2408e02ccb98de9341bb61.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Java开发中,我们常常需要处理一些耗时的任务,比如网络请求、文件读写、复杂计算等等。这些任务如果不能在规定时间内完成,就会导致程序出现阻塞或者超时的情况。为了避免这种情况的发生,我们需要实现一个Java任务超时处理机制。 下面我将介绍一种比较简单的实现方式,希望对大家有所帮助。 1. 创建一个FutureTask对象 首先,我们需要创建一个FutureTask对象来封装我们的任务。FutureTask是Java提供的一个用于异步计算的类,它可以在任务完成后获取计算结果。我们可以通过传递一个Callable对象给FutureTask来构造一个异步任务。 例如,我们要执行一个耗时的函数calculate(),则可以这样创建FutureTask对象: ``` Callable<Integer> callable = new Callable<Integer>() { @Override public Integer call() throws Exception { return calculate(); } }; FutureTask<Integer> futureTask = new FutureTask<>(callable); ``` 2. 创建一个线程来执行任务 接下来,我们需要创建一个线程来执行任务。我们可以使用线程池来管理线程,这样可以避免频繁地创建和销毁线程。在这个例子中,我们创建了一个只有一个线程的线程池。 ``` ExecutorService executorService = Executors.newSingleThreadExecutor(); executorService.submit(futureTask); ``` 3. 设置超时时间并获取结果 现在,我们需要设置一个超时时间,并在规定时间内获取任务的结果。如果超时了,则需要取消任务。 ``` try { Integer result = futureTask.get(500, TimeUnit.MILLISECONDS); System.out.println("计算结果:" + result); } catch (InterruptedException | ExecutionException | TimeoutException e) { System.out.println("计算超时或出现异常:" + e.getMessage()); futureTask.cancel(true); } ``` 在这个例子中,我们设置了超时时间为500毫秒。如果任务在规定时间内完成,就会输出计算结果;否则,就会输出计算超时或出现异常,并取消任务。 完整代码如下: ``` import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.FutureTask; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; public class TimeoutDemo { public static void main(String[] args) { Callable<Integer> callable = new Callable<Integer>() { @Override public Integer call() throws Exception { return calculate(); } }; FutureTask<Integer> futureTask = new FutureTask<>(callable); ExecutorService executorService = Executors.newSingleThreadExecutor(); executorService.submit(futureTask); try { Integer result = futureTask.get(500, TimeUnit.MILLISECONDS); System.out.println("计算结果:" + result); } catch (InterruptedException | ExecutionException | TimeoutException e) { System.out.println("计算超时或出现异常:" + e.getMessage()); futureTask.cancel(true); } executorService.shutdown(); } private static int calculate() throws InterruptedException { Thread.sleep(1000); return 1 + 1; } } ``` 在这个例子中,我们模拟了一个耗时的函数calculate(),它会休眠1秒钟,然后返回2。由于我们设置了500毫秒的超时时间,因此任务会超时并输出计算超时或出现异常。 这就是Java任务超时处理机制的实现方式。通过使用FutureTask和线程池,我们可以很方便地处理耗时的任务,并在规定时间内获取计算结果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值