Skip to content

Commit c52ea54

Browse files
committed
update laravels 3.7.0
Adjust the handling of custom asynchronous events
1 parent f2be5ed commit c52ea54

File tree

10 files changed

+124
-67
lines changed

10 files changed

+124
-67
lines changed

laravel/.env.example

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,4 +75,5 @@ LARAVELS_LISTEN_IP=0.0.0.0
7575
LARAVELS_LISTEN_PORT=5200
7676
LARAVELS_INOTIFY_RELOAD=false
7777
LARAVELS_DAEMONIZE=false
78+
LARAVELS_TIMER=true
7879
# laravels 配置

laravel/app/Events/ApiExcelSwooleEvent.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,15 @@
1010

1111
namespace App\Events;
1212

13+
use App\Listeners\ApiExcelSwooleListener;
1314
use Hhxsv5\LaravelS\Swoole\Task\Event;
1415

1516
class ApiExcelSwooleEvent extends Event
1617
{
18+
protected $listeners = [
19+
ApiExcelSwooleListener::class,
20+
];
21+
1722
private $data;
1823

1924
public function __construct($data)

laravel/app/Events/LoginSwooleEvent.php

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
namespace App\Events;
44

55

6+
use App\Listeners\LoginSwooleListener;
67
use Hhxsv5\LaravelS\Swoole\Task\Event;
78
// use Illuminate\Queue\SerializesModels;
89
// use Illuminate\Foundation\Events\Dispatchable;
@@ -13,7 +14,9 @@
1314

1415
class LoginSwooleEvent extends Event
1516
{
16-
// use Dispatchable, InteractsWithSockets, SerializesModels;
17+
protected $listeners = [
18+
LoginSwooleListener::class,
19+
];
1720

1821
/**
1922
* @var User 用户模型

laravel/app/Events/TestEvent.php

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,16 @@
1010

1111
namespace App\Events;
1212

13+
use App\Listeners\TestListener;
1314
use Hhxsv5\LaravelS\Swoole\Task\Event;
1415

1516
class TestEvent extends Event
1617
{
18+
protected $listeners = [
19+
// Listener list
20+
TestListener::class,
21+
];
22+
1723
private $data;
1824

1925
public function __construct($data)
@@ -25,4 +31,4 @@ public function getData()
2531
{
2632
return $this->data;
2733
}
28-
}
34+
}

laravel/app/Http/Controllers/Api/ApiExcelController.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,7 @@ public function startTask(Request $request)
144144
// 如果是 cli 模式使用 laravels Task 异步事件
145145
if (PHP_SAPI == 'cli' && extension_loaded('swoole')) {
146146
// 触发事件--实例化并通过fire触发,此操作是异步的,触发后立即返回,由Task进程继续处理监听器中的handle逻辑
147+
// \Log::info(__CLASS__.': start task', $data);
147148
$event = new ApiExcelSwooleEvent($data);
148149
// $event = new TestEvent('event data');
149150
// $event->delay(10); // 延迟10秒触发

laravel/app/Listeners/ApiExcelSwooleListener.php

Lines changed: 16 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -10,24 +10,25 @@
1010
namespace App\Listeners;
1111

1212

13+
use App\Events\ApiExcelSwooleEvent;
1314
use App\Http\Repository\MultithreadingRepository;
1415
use App\Models\ApiExcel;
15-
use Hhxsv5\LaravelS\Swoole\Task\Event;
1616
use Hhxsv5\LaravelS\Swoole\Task\Listener;
1717

1818
class ApiExcelSwooleListener extends Listener
1919
{
20-
// 声明没有参数的构造函数
21-
public function __construct()
22-
{
23-
}
20+
/**
21+
* @var ApiExcelSwooleEvent
22+
*/
23+
protected $event;
2424

25-
public function handle(Event $event)
25+
public function handle()
2626
{
27-
\Log::info(__CLASS__.':handle start', [$event->getData()]);
27+
$data = $this->event->getData();
28+
\Log::info(__CLASS__.': handle start', [$data]);
2829
// 获取事件中保存的数据
2930
// $data = ['id' => 6, 'state' => 1, 'upload_url' => '/storage/20190318_103542_5c8f03fe14d89.xlsx'];
30-
$data = $event->getData();
31+
// $data = $event->getData();
3132
// 根据状态处理数据
3233
switch ($data['state']) {
3334
case 1:
@@ -53,7 +54,9 @@ public function handle(Event $event)
5354
// 更新任务失败
5455
$apiExcel->state = 5;
5556
$apiExcel->save();
56-
throw new \Exception(date('Y-m-d H:i:s').' 任务失败: 第三方请求错误~!'.$param['url']);
57+
\Log::error(__CLASS__.': Line '.__LINE__.' - error'.date('Y-m-d H:i:s').' 任务失败: 第三方请求错误~!'.$param['url'], []);
58+
return;
59+
// throw new \Exception(date('Y-m-d H:i:s').' 任务失败: 第三方请求错误~!'.$param['url']);
5760
}
5861

5962
/************************* 2. 写入 Excel 文件 ******************************/
@@ -62,7 +65,9 @@ public function handle(Event $event)
6265
if (!$fileName) {
6366
$apiExcel->state = 5;
6467
$apiExcel->save();
65-
throw new \Exception(date('Y-m-d H:i:s').' 任务失败: Writer\Exception~!');
68+
\Log::error(__CLASS__.': Line '.__LINE__.' - error'.date('Y-m-d H:i:s').' 任务失败: Writer\Exception~!', []);
69+
return;
70+
// throw new \Exception(date('Y-m-d H:i:s').' 任务失败: Writer\Exception~!');
6671
}
6772

6873
// 更新任务状态
@@ -71,7 +76,7 @@ public function handle(Event $event)
7176
$apiExcel->save();
7277
}
7378
} else {
74-
\Log::info(__CLASS__.':handle out', [$event->getData()]);
79+
\Log::info(__CLASS__.': No Task Work, Line '.__LINE__, [$data]);
7580
}
7681
break;
7782
default:

laravel/app/Listeners/LoginSwooleListener.php

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,17 +3,17 @@
33
namespace App\Listeners;
44

55

6-
use Hhxsv5\LaravelS\Swoole\Task\Event;
6+
use App\Events\LoginSwooleEvent;
77
use Hhxsv5\LaravelS\Swoole\Task\Listener;
88
use Illuminate\Support\Facades\DB;
99
use Zhuzhichao\IpLocationZh\Ip;
1010

1111
class LoginSwooleListener extends Listener
1212
{
13-
// 声明没有参数的构造函数
14-
public function __construct()
15-
{
16-
}
13+
/**
14+
* @var LoginSwooleEvent
15+
*/
16+
protected $event;
1717

1818
/**
1919
* 失败重试次数
@@ -24,11 +24,10 @@ public function __construct()
2424

2525
/**
2626
* handle 方法中处理事件
27-
*
28-
* @param Event $event
2927
*/
30-
public function handle(Event $event)
28+
public function handle()
3129
{
30+
$event = $this->event;
3231
// 获取事件中保存的信息
3332
$user = $event->getUser();
3433
$agent = $event->getAgent();

laravel/app/Listeners/TestListener.php

Lines changed: 11 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -9,28 +9,26 @@
99

1010
namespace App\Listeners;
1111

12+
use App\Events\TestEvent;
1213
use App\Tasks\TestTask;
1314
use Hhxsv5\LaravelS\Swoole\Task\Task;
14-
use Hhxsv5\LaravelS\Swoole\Task\Event;
1515
use Hhxsv5\LaravelS\Swoole\Task\Listener;
1616

1717
class TestListener extends Listener
1818
{
19-
// 声明没有参数的构造函数
20-
public function __construct()
21-
{
22-
}
19+
/**
20+
* @var TestEvent
21+
*/
22+
protected $event;
2323

24-
public function handle(Event $event)
24+
public function handle()
2525
{
26-
\Log::info(__CLASS__.':handle start', [$event->getData()]);
26+
\Log::info(__CLASS__.':handle start', [$this->event->getData()]);
2727
sleep(2);// 模拟一些慢速的事件处理
2828
// 监听器中也可以投递Task,但不支持Task的finish()回调。
29-
// 注意:
30-
// 1.参数2需传true
31-
// 2.config/laravels.php中修改配置 task_ipc_mode 为1或2,参考 https://wiki.swoole.com/wiki/page/296.html
32-
// $ret = Task::deliver(new TaskEvent('task data'), true);
33-
// var_dump($ret);
29+
// 注意:config/laravels.php中修改配置task_ipc_mode为1或2,参考 https://wiki.swoole.com/#/server/setting?id=task_ipc_mode
30+
$ret = Task::deliver(new TestTask('task data'));
31+
var_dump($ret);
3432
// throw new \Exception('an exception');// handle时抛出的异常上层会忽略,并记录到Swoole日志,需要开发者try/catch捕获处理
3533
}
36-
}
34+
}

laravel/app/User.php

Lines changed: 40 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,15 @@ class User extends Authenticatable implements JWTSubject
3030
'password', 'remember_token',
3131
];
3232

33+
/**
34+
* The attributes that should be cast to native types.
35+
*
36+
* @var array
37+
*/
38+
protected $casts = [
39+
'email_verified_at' => 'datetime',
40+
];
41+
3342
/**
3443
* @return mixed|string
3544
*/
@@ -109,9 +118,36 @@ public function hasPermissionMy($permissionName)
109118
* @param $permissions []
110119
* @param $option [] valid_all 是否判断全部权限
111120
*
112-
* @var array
121+
* @return array|bool|null
113122
*/
114-
protected $casts = [
115-
'email_verified_at' => 'datetime',
116-
];
123+
function hasPermission($permissions, $option = [])
124+
{
125+
$option = array_merge(['valid_all' => false,], $option);
126+
if (!is_array($permissions)) $permissions = [$permissions];
127+
$gates = cacheUserRolesAndPermissions(\Auth::id(), false);
128+
129+
foreach ($permissions as $permission) {
130+
if (in_array($permission, $gates['permissions'])) {
131+
if (!$option['valid_all']) {
132+
return true;
133+
}
134+
} else {
135+
if ($option['valid_all']) {
136+
return false;
137+
}
138+
}
139+
}
140+
if ($option['valid_all'])
141+
return true;
142+
else
143+
return false;
144+
}
145+
146+
// 给用户分配角色
147+
public function assignRole($role)
148+
{
149+
return $this->roles()->save(
150+
Role::whereName($role)->firstOrFail()
151+
);
152+
}
117153
}

laravel/config/laravels.php

Lines changed: 32 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
'handle_static' => env('LARAVELS_HANDLE_STATIC', false),
1313
'laravel_base_path' => env('LARAVEL_BASE_PATH', base_path()),
1414
'inotify_reload' => [
15-
'enable' => env('LARAVELS_INOTIFY_RELOAD', true),
15+
'enable' => env('LARAVELS_INOTIFY_RELOAD', false),
1616
'watch_path' => base_path(),
1717
'file_types' => ['.php'],
1818
'excluded_dirs' => [],
@@ -23,44 +23,42 @@
2323
'enable' => true, // 看清楚,这里是true
2424
'handler' => \App\Services\WebSocketService::class,
2525
],
26-
'sockets' => [
27-
],
26+
'sockets' => [],
2827
'processes' => [
28+
//[
29+
// 'class' => \App\Processes\TestProcess::class,
30+
// 'redirect' => false, // Whether redirect stdin/stdout, true or false
31+
// 'pipe' => 0 // The type of pipeline, 0: no pipeline 1: SOCK_STREAM 2: SOCK_DGRAM
32+
// 'enable' => true // Whether to enable, default true
33+
//],
2934
],
3035
'timer' => [
31-
'enable' => true, // 开启定时任务类
32-
'jobs' => [
33-
// 启用LaravelScheduleJob来执行`php artisan schedule:run`,每分钟一次,替代Linux Crontab
36+
'enable' => env('LARAVELS_TIMER', true),
37+
'jobs' => [
38+
// 启用LaravelScheduleJob来执行`php artisan schedule:run`,每分钟一次,替代 Linux Crontab
3439
// \Hhxsv5\LaravelS\Illuminate\LaravelScheduleJob::class,
3540
// 两种配置参数的方式:
3641
// [\App\Jobs\Timer\TestCronJob::class, [1000, true]], // 注册时传入参数
3742
// \App\Jobs\Timer\TestCronJob::class, // 重载对应的方法来返回参数
38-
// App\Jobs\Timer\FiveMinutesCronJob::class,
39-
// App\Jobs\Timer\HourlyCronJob::class,
40-
],
41-
'pid_file' => storage_path('laravels-timer.pid'),
42-
'max_wait_time' => 5, // Reload 时最大等待时间
43-
],
44-
// 绑定事件与监听器,一个事件可以有多个监听器,多个监听器按顺序执行
45-
'events' => [
46-
\App\Events\TestEvent::class => [
47-
\App\Listeners\TestListener::class,
48-
],
49-
\App\Events\ApiExcelSwooleEvent::class => [
50-
\App\Listeners\ApiExcelSwooleListener::class,
51-
],
52-
App\Events\LoginSwooleEvent::class => [
53-
App\Listeners\LoginSwooleListener::class,
43+
App\Jobs\Timer\FiveMinutesCronJob::class,
44+
App\Jobs\Timer\HourlyCronJob::class,
5445
],
46+
'max_wait_time' => 5,
5547
],
56-
'swoole_tables' => [
57-
],
58-
'cleaners' => [
48+
'swoole_tables' => [],
49+
'register_providers' => [],
50+
'cleaners' => [
51+
// See LaravelS's built-in cleaners: https://github.com/hhxsv5/laravel-s/blob/master/Settings.md#cleaners
5952
Hhxsv5\LaravelS\Illuminate\Cleaners\SessionCleaner::class, // 如果你的项目中使用到了Session或Authentication,请解除这行注释
6053
Hhxsv5\LaravelS\Illuminate\Cleaners\AuthCleaner::class, // 如果你的项目中使用到了Authentication或Passport,请解除这行注释
6154
Hhxsv5\LaravelS\Illuminate\Cleaners\JWTCleaner::class, // 如果你的项目中使用到了包"tymon/jwt-auth",请解除这行注释
6255
// Hhxsv5\LaravelS\Illuminate\Cleaners\RequestCleaner::class,
63-
//...
56+
],
57+
'destroy_controllers' => [
58+
'enable' => false,
59+
'excluded_list' => [
60+
//\App\Http\Controllers\TestController::class,
61+
],
6462
],
6563
'swoole' => [
6664
'daemonize' => env('LARAVELS_DAEMONIZE', false),
@@ -70,9 +68,9 @@
7068
'worker_num' => function_exists('swoole_cpu_num') ? swoole_cpu_num() * 2 : 8,
7169
'task_worker_num' => function_exists('swoole_cpu_num') ? swoole_cpu_num() * 2 : 8,
7270
'task_ipc_mode' => 1,
73-
'task_max_request' => 8000,
71+
'task_max_request' => env('LARAVELS_TASK_MAX_REQUEST', 8000),
7472
'task_tmpdir' => @is_writable('/dev/shm/') ? '/dev/shm' : '/tmp',
75-
'max_request' => 8000,
73+
'max_request' => env('LARAVELS_MAX_REQUEST', 8000),
7674
'open_tcp_nodelay' => true,
7775
'pid_file' => storage_path('laravels.pid'),
7876
'log_file' => storage_path(sprintf('logs/swoole-%s.log', date('Y-m'))),
@@ -87,9 +85,14 @@
8785
'enable_coroutine' => false,
8886
'http_compression' => false,
8987

88+
// Slow log
89+
// 'request_slowlog_timeout' => 2,
90+
// 'request_slowlog_file' => storage_path(sprintf('logs/slow-%s.log', date('Y-m'))),
91+
// 'trace_event_worker' => true,
92+
9093
/**
9194
* More settings of Swoole
92-
* @see https://wiki.swoole.com/wiki/page/274.html Chinese
95+
* @see https://wiki.swoole.com/#/server/setting Chinese
9396
* @see https://www.swoole.co.uk/docs/modules/swoole-server/configuration English
9497
*/
9598
],

0 commit comments

Comments
 (0)