業(yè)務(wù)需求
app客戶端向服務(wù)端接口發(fā)送來(lái)json 數(shù)據(jù) 每天 發(fā)一次 清空緩存后會(huì)再次發(fā)送
出問(wèn)題之前業(yè)務(wù)邏輯:
php 接口 首先將 json 轉(zhuǎn)為數(shù)組 去重 在一張大表中插入不存在的數(shù)據(jù)
該用戶已經(jīng)存在 和新增的id
入另一種詳情表
問(wèn)題所在:
當(dāng)用戶因特殊情況清除緩存 導(dǎo)致app 發(fā)送json串 入庫(kù)并發(fā)高 導(dǎo)致CPU 暴增到88% 并且居高不下
優(yōu)化思路:
1、異步隊(duì)列處理
2、redis 過(guò)濾(就是只處理當(dāng)天第一次請(qǐng)求)
3、redis 輔助存儲(chǔ)app名稱(chēng)(驗(yàn)證過(guò)后批量插入數(shù)據(jù)app名稱(chēng)表中)
4、拼接插入的以及新增的如詳細(xì)表中
解決辦法:
1、接口修改 redis 過(guò)濾 + 如list隊(duì)列 并將結(jié)果存入redis中
首先 redis將之前的歷史數(shù)據(jù)放在redis 哈希里面 中文為鍵名 id 為鍵值
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
|
<?php /** * Created by haiyong. * User: jia * Date: 2017/9/18 * Time: 20:06 */ namespace App\Http\Controllers\App; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Redis; class OtherAppController extends Controller{ /** * app應(yīng)用統(tǒng)計(jì)接口 * @param Request $request * @return string */ public function appTotal(Request $request ) { // //歷史數(shù)據(jù)入庫(kù) //$redis = Redis::connection('web_active'); // $app_name = DB::connection('phpLog')->table('app_set_name')->where("appName", '<>', ' ')->lists('id', 'appName'); // $str = ''; // foreach ($app_name as $key => $val) { // $str.= "{$val} {$key} "; // } // $redis->hmset('app_name', $app_name); // echo $str;exit; $result = $request ->input( 'res' ); $list = json_decode( $result , true); if ( empty ( $list ) || ! is_array ( $list )) { return json_encode([ 'result' => 'ERROR' , 'msg' => 'parameter error' ]); } $data [ 'uid' ] = isset( $list [ 'uid' ]) ? $list [ 'uid' ] : '20001' ; $data [ 'time' ] = date ( 'Y-m-d' ); $redis_key = 'log_app:' . $data [ 'time' ]; //redis 過(guò)濾 $redis = Redis::connection( 'web_active' ); //redis 鍵值過(guò)期設(shè)置 if ( empty ( $redis ->exists( $redis_key ))) { $redis ->hset( $redis_key , 1, 'start' ); $redis ->EXPIREAT( $redis_key , strtotime ( $data [ 'time' ]. '+2 day' )); } //值確定 if ( $redis ->hexists( $redis_key , $data [ 'uid' ])) { return json_encode([ 'result' => 'SUCCESS' ]); } else { //推入隊(duì)列 $redis ->hset( $redis_key , $data [ 'uid' ], $result ); $redis ->rpush( 'log_app_list' , $data [ 'time' ] . ':' . $data [ 'uid' ]); return json_encode([ 'result' => 'SUCCESS' ]); } } } |
2、php 腳本循環(huán) 監(jiān)控redis 隊(duì)列 執(zhí)行邏輯 防止內(nèi)存溢出
mget 獲取該用戶的app id 不存在就會(huì)返回null
通過(guò)判斷null 運(yùn)用redis 新值作為自增id指針 將null 補(bǔ)齊 之后批量入mysql 并跟新redis 哈希 和指針值 并入庫(kù) 詳情表
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
|
<?php namespace App\Console\Commands; use Illuminate\Console\Command; use Illuminate\Support\Facades\Redis; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Storage; class AppTotal extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'AppTotal:run' ; /** * The console command description. * * @var string */ protected $description = 'Command description' ; /** * Create a new command instance. * * @return void */ public function __construct() { parent::__construct(); } /** * Execute the console command. * * @return mixed */ public function handle() { //歷史數(shù)據(jù)入庫(kù) // $redis = Redis::connection('web_active'); // $app_name = DB::connection('phpLog')->table('app_set_name')->where("appName", '<>', ' ')->lists('id', 'appName'); // $redis->hmset('app_name', $app_name); // exit; while (1) { $redis = Redis::connection( 'web_active' ); //隊(duì)列名稱(chēng) $res = $redis ->lpop( 'log_app_list' ); //開(kāi)關(guān)按鈕 $lock = $redis ->get( 'log_app_lock' ); if (! empty ( $res )) { list( $date , $uid ) = explode ( ':' , $res ); $result = $redis ->hget( 'log_app:' . $date , $uid ); if (! empty ( $result )) { $table_name = 'app_total' . date ( 'Ym' ); $list = json_decode( $result , true); $data [ 'uid' ] = isset( $list [ 'uid' ]) ? $list [ 'uid' ] : '20001' ; $data [ 'sex' ] = isset( $list [ 'sex' ]) ? $list [ 'sex' ] : '' ; $data [ 'device' ] = isset( $list [ 'device' ]) ? $list [ 'device' ] : '' ; $data [ 'appList' ] = isset( $list [ 'list' ]) ? $list [ 'list' ] : '' ; //數(shù)據(jù)去重 flip比unique更節(jié)約性能 $data [ 'appList' ] = array_flip ( $data [ 'appList' ]); $data [ 'appList' ] = array_flip ( $data [ 'appList' ]); $data [ 'time' ] = date ( 'Y-m-d' ); //app應(yīng)用過(guò)濾 $app_res = $redis ->hmget( 'app_name' , $data [ 'appList' ]); //新增加app數(shù)組 $new_app = []; //mysql 入庫(kù)數(shù)組 $mysql_new_app = []; //獲取當(dāng)前redis 自增指針 $total = $redis ->get( 'app_name_total' ); foreach ( $app_res as $key =>& $val ) { if ( is_null ( $val )) { $total += 1; $new_app [ $data [ 'appList' ][ $key ]] = $total ; $val = $total ; array_push ( $mysql_new_app ,[ 'id' => $total , 'appName' => $data [ 'appList' ][ $key ]]); } } if ( count ( $new_app )){ $str = "INSERT IGNORE INTO app_set_name (id,appName) values" ; foreach ( $new_app as $key => $val ) { $str .= "(" . $val . ",'" . $key . "')," ; } $str = trim( $str , ',' ); //$mysql_res = DB::connection('phpLog')->table('app_set_name')->insert($mysql_new_app); $mysql_res = DB::connection( 'phpLog' )->statement( $str ); if ( $mysql_res ) { // 設(shè)置redis 指針 $redis ->set( 'app_name_total' , $total ); // redis 數(shù)據(jù)入庫(kù) $redis ->hmset( 'app_name' , $new_app ); } } // 詳情數(shù)據(jù)入庫(kù) $data [ 'appList' ] = implode( ',' , $app_res ); //app統(tǒng)計(jì)入庫(kù) DB::connection( 'phpLog' )->statement( "INSERT IGNORE INTO " . $table_name ." (uid,sex,device,`time`,appList) values( '".$data[' uid ']."' , ".$data['sex']." , '".$data[' device ']."' , '".$data[' time ']."' , '".$data[' appList ']."' )"); //log 記錄 當(dāng)文件達(dá)到123MB的時(shí)候產(chǎn)生內(nèi)存保錯(cuò) 所有這個(gè)地方可是利用日志切割 或者 不寫(xiě)入 日志 Storage::disk( 'local' )->append(DIRECTORY_SEPARATOR. 'total' .DIRECTORY_SEPARATOR. 'loaAppTotal.txt' , date ( 'Y-m-d H:i:s' ). ' success ' . $result . "\n" ); } else { Storage::disk( 'local' )->append(DIRECTORY_SEPARATOR. 'total' .DIRECTORY_SEPARATOR. 'loaAppTotal.txt' , date ( 'Y-m-d H:i:s' ). ' error ' . $result . "\n" ); } } //執(zhí)行間隔 sleep(1); //結(jié)束按鈕 if ( $lock == 2) { exit ; } //內(nèi)存檢測(cè) if (memory_get_usage()>1000*1024*1024){ exit ( '內(nèi)存溢出' ); //大于100M內(nèi)存退出程序,防止內(nèi)存泄漏被系統(tǒng)殺死導(dǎo)致任務(wù)終端 } } } } |
3、執(zhí)定 定時(shí)任務(wù)監(jiān)控腳本執(zhí)行情況
1
2
3
|
crontab -e /2 * * * * /bin/bash /usr/ local /nginx/html/test.sh 1>>/usr/ local /nginx/html/log.log 2>&1 |
test.sh 內(nèi)容 (查看執(zhí)行命令返回的進(jìn)程id 如果沒(méi)有就執(zhí)行命令開(kāi)啟)
1
2
3
4
5
6
|
#!/bin/bash alive=`ps -ef | grep AppTotal | grep -v grep | awk '{print $2}' ` if [ ! $alive ] then /usr/ local /php/bin/php /var/ms/artisan AppTotal:run > /dev/ null & fi |
記得授權(quán)哦 chmod +x test.sh
筆者用的laravel 框架 將命令激活丟入后臺(tái)
執(zhí)行命令
1
|
/usr/ local /php/bin/php /var/ms/artisan AppTotal:run > /dev/ null & |
完事直接 ctrl -c 結(jié)束就行 命令以在后臺(tái)運(yùn)行 可以用shell 中的命令查看進(jìn)程id
這樣就實(shí)現(xiàn)隊(duì)列異步入庫(kù)
還有很多問(wèn)題需要優(yōu)化?。〈笾鹿δ芤呀?jīng)實(shí)現(xiàn)!?。。。。?/p>
優(yōu)化完成后cpu
以上這篇異步redis隊(duì)列實(shí)現(xiàn) 數(shù)據(jù)入庫(kù)的方法就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://blog.csdn.net/woshihaiyong168/article/details/79110608