Skip to content

Commit b2c5f34

Browse files
committed
!2 WebSocket 表格中的使用
Merge pull request !2 from lisgroup/develop
2 parents ff34609 + 233c094 commit b2c5f34

32 files changed

+808
-52
lines changed

admin/config/dev.env.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,4 +5,5 @@ const prodEnv = require('./prod.env')
55
module.exports = merge(prodEnv, {
66
NODE_ENV: '"development"',
77
BASE_API: '"http://localhost:8000"',
8+
WEBSOCKET: '"ws://127.0.0.1:5200"',
89
})

admin/config/prod.env.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,4 +2,5 @@
22
module.exports = {
33
NODE_ENV: '"production"',
44
BASE_API: '"https://www.guke1.com"',
5+
WEBSOCKET: '"wss://www.guke1.com/ws"',
56
}

admin/src/views/api_excel/index.vue

Lines changed: 41 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
<el-button type="primary" size="medium">
55
<router-link to="/api_excel/add">上传测试</router-link>
66
</el-button>
7+
<el-button :loading="reload" type="primary" class="reload" plain @click="fetchData">{{ reload_name }}</el-button>
78
</el-row>
89
<el-table
910
v-loading="listLoading"
@@ -55,7 +56,7 @@
5556
</template>
5657
</el-table-column>
5758

58-
<el-table-column label="进度条" width="1" align="center" display="none">
59+
<el-table-column label="进度条" width="100" align="center" display="none">
5960
<template slot-scope="scope">
6061
<div v-if="scope.row.state === 0">
6162
<el-progress :text-inside="true" :stroke-width="18" :percentage="0"/>
@@ -67,7 +68,7 @@
6768
<el-progress :text-inside="true" :stroke-width="18" :percentage="100" status="success"/>
6869
</div>
6970
<div v-else>
70-
<el-progress :text-inside="true" :stroke-width="18" :percentage="50" status="exception"/>
71+
<el-progress :text-inside="true" :stroke-width="18" :percentage="scope.row.rate" status="exception"/>
7172
</div>
7273
</template>
7374
</el-table-column>
@@ -126,6 +127,7 @@
126127
</template>
127128

128129
<script>
130+
import { getToken } from '@/utils/auth'
129131
import { getList, deleteAct, search, startTask, download_log } from '@/api/api_excel'
130132
131133
export default {
@@ -141,6 +143,8 @@ export default {
141143
},
142144
data() {
143145
return {
146+
reload: false,
147+
reload_name: '点击刷新',
144148
list: null,
145149
listLoading: true,
146150
perpage: 10,
@@ -156,7 +160,8 @@ export default {
156160
this.currentpage = parseInt(this.listQuery.page)
157161
const perPage = parseInt(this.$route.query.perPage)
158162
this.perpage = isNaN(perPage) ? this.perpage : perPage
159-
this.fetchData()
163+
// this.fetchData()
164+
this.initWebSocket()
160165
},
161166
destroyed() {
162167
this.websock.close() // 离开路由之后断开 websocket 连接
@@ -209,20 +214,22 @@ export default {
209214
type: msg,
210215
message: res.reason
211216
})
217+
this.initWebSocket()
212218
})
213219
}
214220
}
215221
})
216222
},
217-
initWebSocket(id) { // 初始化 weosocket
223+
initWebSocket() { // 初始化 weosocket
218224
if ('WebSocket' in window) {
219-
const url = 'wss://www.guke1.com/ws?id=' + id
225+
const url = process.env.WEBSOCKET + '?action=api_excel&token=' + getToken()
220226
this.websock = new WebSocket(url)
221227
this.websock.onmessage = this.onmessage
222228
this.websock.onopen = this.onopen
223229
this.websock.onerror = this.onerror
224230
this.websock.onclose = this.close
225231
} else {
232+
this.fetchData()
226233
// 浏览器不支持 WebSocket,使用 ajax 轮询
227234
console.log('Your browser does not support WebSocket!')
228235
}
@@ -232,44 +239,60 @@ export default {
232239
// const rs = this.send(JSON.stringify(actions))
233240
// console.log(rs)
234241
},
235-
onerror() { // 连接建立失败重连
242+
onerror() {
243+
// 连接建立失败, 发送 http 请求获取数据
236244
// this.initWebSocket()
245+
this.fetchData()
237246
},
238247
onmessage(e) { // 数据接收
239-
console.log(e.data)
248+
// console.log(e.data)
240249
const data = JSON.parse(e.data)
241250
// this.list[2].rate = parseInt(data.data.rate)
242251
// console.log(this.list[2].rate)
243-
console.log(data)
252+
// console.log(data)
253+
// websocket 返回的数据
254+
this.list = data.data.data
255+
this.listLoading = false
256+
this.total = data.data.total
257+
this.url = data.data.appUrl
258+
// console.log('type', Object.prototype.toString.call(this.list))
259+
setTimeout(() => {
260+
this.reload = false
261+
this.reload_name = '刷新'
262+
}, 800)
244263
},
245264
send(Data) {
246265
this.websock.send(Data)
247266
},
248267
close() { // 关闭
249-
console.log('断开连接')
268+
// console.log('断开连接')
250269
},
251270
download(index, row) {
252271
window.location.href = this.url + row.finish_url
253272
},
254273
download_log(index, row) {
255274
download_log({ id: row.id }).then(res => {
256-
console.log(res)
275+
// console.log(res)
257276
if (res.code === 200) {
258277
window.location.href = this.url + res.data.failed_done_file
259278
}
260279
})
261280
},
262281
fetchData() {
263-
this.listLoading = true
282+
this.listLoading = this.reload = true
283+
this.reload_name = '加载中'
264284
const params = Object.assign({ 'page': this.listQuery.page }, { 'perPage': this.perpage })
265285
getList(params).then(response => {
266286
this.list = response.data.data
267287
this.listLoading = false
268288
this.total = response.data.total
269289
this.url = response.data.appUrl
270-
console.log('type', Object.prototype.toString.call(this.list))
271-
272-
this.initWebSocket(8)
290+
// console.log('type', Object.prototype.toString.call(this.list))
291+
setTimeout(() => {
292+
this.reload = false
293+
this.reload_name = '刷新'
294+
}, 800)
295+
// this.initWebSocket()
273296
})
274297
},
275298
handleEdit(index, row) {
@@ -354,4 +377,8 @@ export default {
354377
.pagination {
355378
margin: 20px auto;
356379
}
380+
.reload {
381+
margin-right: 300px;
382+
float: right;
383+
}
357384
</style>
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
<?php
2+
3+
namespace App\Events;
4+
5+
use Illuminate\Broadcasting\Channel;
6+
use Illuminate\Queue\SerializesModels;
7+
use Illuminate\Broadcasting\PrivateChannel;
8+
use Illuminate\Foundation\Events\Dispatchable;
9+
use Illuminate\Broadcasting\InteractsWithSockets;
10+
11+
class SaveApiExcelLogEvent
12+
{
13+
use Dispatchable, InteractsWithSockets, SerializesModels;
14+
15+
/**
16+
* @var array api_excel 表中数据
17+
*/
18+
private $data;
19+
20+
/**
21+
* 实例化事件时传递参数
22+
*
23+
* ApiExcelEvent constructor.
24+
* @param array $data
25+
*/
26+
public function __construct($data)
27+
{
28+
$this->data = $data;
29+
}
30+
31+
/**
32+
* 获取 $data
33+
*
34+
* @return array
35+
*/
36+
public function getData()
37+
{
38+
return $this->data;
39+
}
40+
41+
/**
42+
* Get the channels the event should broadcast on.
43+
*
44+
* @return Channel|array
45+
*/
46+
public function broadcastOn()
47+
{
48+
return new PrivateChannel('channel-default');
49+
}
50+
}

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

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
namespace App\Http\Controllers\Api;
44

55
use App\Events\ApiExcelEvent;
6+
use App\Http\Repository\ApiRepository;
67
use App\Http\Repository\ExcelRepository;
78
use App\Http\Requests\ApiExcel\Store;
89
use App\Http\Requests\ApiExcel\Update;
@@ -57,6 +58,8 @@ public function index()
5758
$where = ['uid' => $user_id];
5859
}
5960
$list = ApiExcel::with('apiParam')->where($where)->orderBy('id', 'desc')->paginate($this->perPage);
61+
// 获取完成进度情况
62+
$list = ApiRepository::getInstent()->workProgress($list);
6063

6164
$appUrl = env('APP_URL') ?? '';
6265
$collect = collect(['appUrl' => $appUrl]);
@@ -264,6 +267,11 @@ public function forceDelete($id)
264267
return $this->out(200);
265268
}
266269

270+
/**
271+
* 下载已完成数据
272+
*
273+
* @return \Illuminate\Http\Response
274+
*/
267275
public function downloadLog()
268276
{
269277
$api_excel_id = $this->request->input('id');
@@ -280,4 +288,5 @@ public function downloadLog()
280288
}
281289
return $this->out(200, ['failed_done_file' => $failed_done_file]);
282290
}
291+
283292
}

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,7 @@ public function store(Store $request)
6868
// 会出现 Unknown column 'guid' in 'field list' 不存在的字段入库报错问题
6969
// $rs = ApiParam::insert($request->all());
7070
$input = $request->all();
71+
$input['website'] = $input['website'] ?? '';
7172
$model = new ApiParam($input);
7273
if ($model->save()) {
7374
return $this->out(200, ['data' => ['id' => $model->id]]);

laravel/app/Http/Repository/ApiRepository.php

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

1111

1212
use App\Models\ApiExcel;
13+
use App\Models\ApiExcelLogs;
1314

1415
class ApiRepository
1516
{
@@ -75,7 +76,6 @@ public function autoFailed()
7576
// 开启任务后 10 分钟未查询出结果=》失败
7677
if ($excel['auto_delete'] > 0 && strtotime($excel['updated_at']) + 600 < time()) {
7778
ApiExcel::where('id', $excel['id'])->update(['state' => 5]);
78-
7979
}
8080

8181
}
@@ -107,4 +107,54 @@ public function randomTime()
107107
{
108108
return (float)sprintf('%.0f', microtime(true) * 1000);
109109
}
110+
111+
112+
/**
113+
* 获取下载进度条
114+
*
115+
* @param $lists
116+
*
117+
* @return mixed
118+
*/
119+
public function workProgress($lists)
120+
{
121+
foreach ($lists as $key => $list) {
122+
$rate = 100;
123+
switch ($list['state']) {
124+
case '0': // 未开启任务
125+
$rate = 0;
126+
break;
127+
case '1': // 正在处理的任务
128+
case '5': // 失败任务
129+
$rate = $this->progressRate($list['id'], $list['total_excel']);
130+
break;
131+
}
132+
133+
$lists[$key]['rate'] = $rate;
134+
}
135+
return $lists;
136+
}
137+
138+
139+
/**
140+
* 计算任务完成百分比
141+
*
142+
* @param int $excel_id api_excel 主键 id
143+
* @param int $total_excel 总数
144+
*
145+
* @return int|bool
146+
*/
147+
private function progressRate($excel_id, $total_excel)
148+
{
149+
if ($total_excel > 0) {
150+
// 2. 查询 api_excel_logs 表更新的数据量
151+
$total = ApiExcelLogs::where('api_excel_id', $excel_id)->count();
152+
// 3. 返回完成率
153+
$rate = floor($total / $total_excel * 100);
154+
return $rate > 100 ? 100 : $rate;
155+
}
156+
157+
return 100;
158+
}
159+
110160
}

laravel/app/Http/Repository/ExcelRepository.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -183,7 +183,7 @@ public function saveExcel($param, $result, $file = '')
183183

184184
$i = 'A';
185185
foreach ($keys as $num => $key) {
186-
$setActive->setCellValue($i.$number, "\t".$value['param'][$key]);
186+
$setActive->setCellValue($i.$number, "\t".($value['param'][$key] ?? ''));
187187
$i++;
188188
}
189189

@@ -240,7 +240,7 @@ public function saveExcel($param, $result, $file = '')
240240
$objActSheet = $objPHPExcel->getActiveSheet();
241241
// 位置bbb *为下文代码位置提供锚
242242
// 给当前活动的表设置名称
243-
$objActSheet->setTitle('Simple');
243+
$objActSheet->setTitle('Sheet1');
244244
// 代码还没有结束,可以复制下面的代码来决定我们将要做什么
245245

246246
// 1,直接生成一个文件

0 commit comments

Comments
 (0)