Redis类:
<?php
namespace Utils ;
use Phalcon\ Config\ Adapter\ Ini as ConfigIni;
class Redis {
private static $redis1 ;
private static $session ;
public static function getObj ( $name = 'redis1' )
{
try {
if ( ! empty ( self: : $$name ) ) {
return self: : $$name ;
}
$config = new ConfigIni ( APP_PATH . "/config" . ENV . "/redis.ini" ) ;
self: : $$name = new \ Redis( ) ;
self: : $$name - > connect ( $config [ $name ] [ 'host' ] , $config [ $name ] [ 'port' ] , 2 ) ;
if ( isset ( $config [ $name ] [ 'password' ] ) && ! empty ( $config [ $name ] [ 'password' ] ) ) {
self: : $$name - > auth ( $config [ $name ] [ 'password' ] ) ;
}
self: : $$name - > select ( $config [ $name ] [ 'database' ] ) ;
} catch ( \ Exception $exception ) {
self: : $$name = false ;
}
return self: : $$name ;
}
} ;
定时任务:
public function orderAction ( )
{
error_reporting ( E_ALL & ~ E_NOTICE ) ;
$redis = Redis: : getObj ( ) ;
$db = $this - > getDI ( ) - > getShared ( 'db' ) ;
while ( true ) {
print_r ( ' -start- ' ) ;
$order_status = 1 ;
file_put_contents ( APP_PATH . "/../domain_order.log" , time ( ) ) ;
try {
$db - > query ( "select 1" ) ;
$order_info = $redis - > lPop ( 'order' ) ;
if ( ! $order_info ) {
echo ' -empty- ' ;
sleep ( 1 ) ;
continue ;
}
$order_info = json_decode ( $order_info , true ) ;
$model_order_info = NetUserOrder: : findFirst ( [ 'order_sn = :order_sn:' , 'bind' = > [ 'order_sn' = > $order_domain_info_save - > order_sn ] ] ) ;
if ( $model_order_info - > pay_status != 200 ) {
echo 'no pay' ;
continue ;
}
if ( $order_domain_info_save - > order_status == 3 ) {
echo ' -Operated- ' ;
continue ;
}
$db - > begin ( ) ;
这里执行订单流程操作
$order_status = 3 ;
$order_domain_info_save - > order_status = $order_status ;
$order_domain_info_save - > operation_time = time ( ) ;
$order_domain_info_save - > update ( ) ;
}
$db - > commit ( ) ;
printf ( '### succ order_id' . $order_info [ 'id' ] . ' ###' ) ;
} catch ( \ Exception $e ) {
$db - > rollback ( ) ;
$order_status = 2 ;
$order_domain_info_save - > order_status = $order_status ;
$order_domain_info_save - > operation_time = time ( ) ;
$order_domain_info_save - > update ( ) ;
printf ( ' error ' . $e - > getMessage ( ) . ' ' ) ;
Log: : error ( $e - > getMessage ( ) ) ;
$redis - > hSet ( 'order_domain_retry' , 'domain_retry_' . $order_info [ 'id' ] , json_encode ( $order_info ) ) ;
}
Redis常用队列方法:
$Redis - > lPop ( $key ) ;
$Redis - > rPush ( $key ) ;
$Redis - > rPop ( $key ) ;
$Redis - > rPop ( $key ) ;
$redis - > lRange ( $key , 0 , - 1 ) ;
Redis 命令参考