fix: 重构tool的ps页面

This commit is contained in:
TsMask
2024-09-06 19:57:10 +08:00
parent 23007c3bf2
commit 57b5f76db7
3 changed files with 298 additions and 283 deletions

View File

@@ -2104,19 +2104,17 @@ export default {
hostSelectHeader: "Host List", hostSelectHeader: "Host List",
}, },
ps:{ ps:{
hour:"h", realTimeHigh:"High",
min:"min", realTimeLow:"Low",
sec:"s", realTimeRegular:"Regular",
fastSpeed:"fast", realTimeStop:"Stop",
normalSpeed:"normal", realTime:"Real Time Speed",
slowSpeed:"slow", pid:"PID",
changeTime:"Refresh rate", name:"APP Name",
PID:"PID", username:"User Name",
name:"APP name", runTime:"Run Time",
username:"User name", numThreads:"Thread",
workTime:"workTime", cpuPercent:"CPU Percent",
numThreads:"numThreads",
cpuPercent:"cpu Percent",
diskRead:"Disk Read", diskRead:"Disk Read",
diskWrite:"Disk Write", diskWrite:"Disk Write",
}, },

View File

@@ -2104,21 +2104,19 @@ export default {
hostSelectHeader: "主机列表", hostSelectHeader: "主机列表",
}, },
ps:{ ps:{
hour:"", realTimeHigh:"",
min:"", realTimeLow:"",
sec:"", realTimeRegular:"常规",
fastSpeed:"快速", realTimeStop:"已暂停",
normalSpeed:"正常", realTime:"实时更新速度",
slowSpeed:"缓慢", pid:"PID",
changeTime:"刷新频率",
PID:"PID",
name:"应用名称", name:"应用名称",
username:"用户名", username:"用户名",
workTime:"运行时间", runTime:"运行时间",
numThreads:"线程数", numThreads:"线程数",
cpuPercent:"CPU使用率", cpuPercent:"CPU使用率",
diskRead:"磁盘读取", diskRead:"磁盘读取",
diskWrite:"磁盘写入", diskWrite:"磁盘写入",
}, },
net:{ net:{
PID:"PID", PID:"PID",

View File

@@ -1,302 +1,291 @@
<script setup lang="ts"> <script setup lang="ts">
import { reactive, onMounted, onBeforeUnmount, nextTick } from 'vue';
import { reactive ,toRaw, onMounted } from 'vue';
import { PageContainer } from 'antdv-pro-layout'; import { PageContainer } from 'antdv-pro-layout';
import { SizeType } from 'ant-design-vue/lib/config-provider';
import { ColumnsType } from 'ant-design-vue/lib/table'; import { ColumnsType } from 'ant-design-vue/lib/table';
import useI18n from '@/hooks/useI18n'; import useI18n from '@/hooks/useI18n';
import { OptionsType, WS } from '@/plugins/ws-websocket'; import { OptionsType, WS } from '@/plugins/ws-websocket';
import { import { RESULT_CODE_ERROR } from '@/constants/result-constants';
RESULT_CODE_ERROR import { diffValue, parseDuration } from '@/utils/date-utils';
} from '@/constants/result-constants'; import { parseSizeFromFile } from '@/utils/parse-utils';
const { t } = useI18n(); const { t } = useI18n();
const ws = new WS(); const ws = new WS();
//查询数据 /**表单查询参数 */
let queryParams = reactive({ let queryParams = reactive({
pid: undefined, pid: undefined,
name:"", name: '',
username:"", username: '',
flag: false,
changeTime:5000,
}); });
//临时缓存 /**状态对象 */
let queryParams2 = reactive({ let state = reactive({
/**调度器 */
interval: null as any,
/**刷新周期 */
intervalTime: 5_000,
/**查询参数 */
query: {
pid: undefined, pid: undefined,
name:"", name: '',
username:"", username: '',
flag: false, },
changeTime:5000,
})
//时间粒度
let timeOptions =[
{label:t('views.tool.ps.fastSpeed'),value:3000},
{label:t('views.tool.ps.normalSpeed'),value:5000},
{label:t('views.tool.ps.slowSpeed'),value:10000},
];
/**钩子函数,界面打开初始化*/
onMounted(() =>{
fnRealTime()//建立连接
extracted()//先立刻发送请求获取第一次的数据
queryReset2(false)//设置定时器
}); });
/**查询按钮**/ /**接收数据后回调(成功) */
function queryTime(){//将表单中的数据传递给缓存数据(缓存数据自动同步请求信息中) function wsMessage(res: Record<string, any>) {
queryParams2.pid=queryParams.pid; const { code, requestId, data } = res;
queryParams2.username=queryParams.username; if (code === RESULT_CODE_ERROR) {
queryParams2.name=queryParams.name; console.warn(res.msg);
//queryParams.flag = true return;
queryParams2.flag=true
queryParams.pid=undefined;
queryParams.name="";
queryParams.username="";
} }
/**重置按钮**/ // 建联时发送请求
function queryReset(){ if (!requestId && data.clientId) {
queryParams.flag = false fnGetList();
queryParams2.flag = false return;
} }
let s:any = null // 收到消息数据
/**定时器**/ if (requestId.startsWith('ps_')) {
function queryReset2(c:boolean){ // 将数据填入表格
if(c){ if (Array.isArray(data)) {
clearInterval(s)//清理旧定时器 tableState.data = data;
ws.close();//断开原来的wb连接 } else {
fnRealTime();//建立新的实时数据连接 tableState.data = [];
}
} }
s = setInterval(()=>{//设置新的定时器s
extracted();
},queryParams.changeTime)
} }
/**刷新频率改变**/ /**实时数据*/
function fnRealTime2() {//时间粒度改变时触发 function fnRealTime(reLink: boolean) {
queryReset2(true)//改变定时器 if (reLink) {
ws.close();
} }
/**
* 实时数据
*/
function fnRealTime() {
const options: OptionsType = { const options: OptionsType = {
url: '/ws', url: '/ws',
onmessage: wsMessage, onmessage: wsMessage,
onerror: wsError, onerror: (ev: any) => {
// 接收数据后回调
console.error(ev);
},
}; };
//建立连接 //建立连接
ws.connect(options); ws.connect(options);
} }
/**接收数据后回调(失败) */ /**调度器周期变更*/
function wsError(ev: any) { function fnIntervalChange(v: any) {
// 接收数据后回调 clearInterval(state.interval);
console.error(ev); const timer = parseInt(v);
if (timer > 1_000) {
state.intervalTime = v;
fnGetList();
}
} }
/**接收数据后回调(成功) */ /**查询列表 */
function wsMessage(res: Record<string, any>) { function fnGetList() {
const { code, requestId, data } = res;//获取数据 if (tableState.loading || ws.state() === -1) return;
if (code === RESULT_CODE_ERROR) { tableState.loading = true;
console.warn(res.msg); const msg = {
return; requestId: `ps_${state.interval}`,
} type: 'ps',
// 处理 data.startTime转换成运行时间并赋值到新的数组processedData data: state.query,
let processedData: any; };
// 首发
if (Array.isArray(data)) { ws.send(msg);
processedData = data.map(item => { // 定时刷新数据
if (item.startTime) {//startTime有值 state.interval = setInterval(() => {
return { ...item, runTime: calculateRunTime(item.startTime) }; msg.data = state.query;
} ws.send(msg);
return item; }, state.intervalTime);
}); tableState.loading = false;
} else if (data && data.startTime) {
processedData = { ...data, runTime: calculateRunTime(data.startTime) };
} else {
processedData = data; // 如果没有 startTime则不做处理
} }
if (requestId) { /**查询参数传入 */
tableState.data = processedData; // 将数据填入表格 function fnQuery() {
} state.query = JSON.parse(JSON.stringify(queryParams));
} nextTick(() => {
/**处理开始时间**/
function calculateRunTime(startTime: string): string {
// 解析开始时间
const startDate = new Date(startTime);
// 获取当前时间
const currentDate = new Date();
// 计算时间差(以毫秒为单位)
const timeDifference = currentDate.getTime() - startDate.getTime();
// 将时间差转换为小时、分钟和秒
const secondsInHour = 3600;
const secondsInMinute = 60;
const totalSeconds = Math.floor(timeDifference / 1000);
const hours = Math.floor(totalSeconds / secondsInHour);
const minutes = Math.floor((totalSeconds % secondsInHour) / secondsInMinute);
const seconds = totalSeconds % secondsInMinute;
return `${hours}${t('views.tool.ps.hour')}${minutes}${t('views.tool.ps.min')} ${seconds}${t('views.tool.ps.sec')}`;// 格式化为字符串
}
function extracted() {//将表单各条件值取出并打包在data中发送请求
const {pid,name, username, flag} = toRaw(queryParams2)//从queryParams中取出各属性值
let data = {} // { 'PID': PID, 'name': name, 'username': username }
if (flag){//若flag为真则把值封装进data
data = { 'PID': pid, 'name': name, 'username': username }
}
//发送请求
ws.send({ ws.send({
'requestId': 'dxxx', requestId: `ps_${state.interval}`,
'type': 'ps', type: 'ps',
'data': data, data: state.query,
});
}); });
} }
/**表格状态 */ /**查询参数重置 */
let tableState: TableStateType = reactive({ function fnQueryReset() {
loading: false, Object.assign(queryParams, {
size: 'large', pid: undefined,
data: [], name: '',
username: '',
}); });
tablePagination.current = 1;
tablePagination.pageSize = 20;
// 重置查询条件
Object.assign(state.query, {
pid: undefined,
name: '',
username: '',
});
}
/**表格状态类型 */ /**表格状态类型 */
type TableStateType = { type TableStateType = {
/**加载等待 */ /**加载等待 */
loading: boolean; loading: boolean;
/**紧凑型 */
size: SizeType;
/**记录数据 */ /**记录数据 */
data: object[]; data: object[];
}; };
/**表格状态 */
let tableState: TableStateType = reactive({
loading: false,
data: [],
});
/**表格字段列 */ /**表格字段列 */
const tableColumns: ColumnsType<any> = [ const tableColumns: ColumnsType<any> = [
{ {
title: t('views.tool.ps.PID'), title: t('views.tool.ps.pid'),
dataIndex: 'PID', dataIndex: 'pid',
align: 'center', align: 'right',
width: 50, width: 100,
sorter:{//PID排序 sorter: {
compare:(a:any, b:any)=>a.PID-b.PID, compare: (a: any, b: any) => a.pid - b.pid,
multiple: 3, multiple: 3,
}
},
{
title: t('views.tool.ps.name'),
dataIndex: 'name',
align: 'center',
width: 100,
},
{
title: t('views.tool.ps.username'),
dataIndex: 'username',
align: 'center',
width: 70,
},
{
title: t('views.tool.ps.workTime'),
dataIndex:'runTime',
align: 'center',
width: 100,
},
{
title: t('views.tool.ps.numThreads'),
dataIndex: 'numThreads',
align: 'center',
width: 70,
sorter:{//线程数比较大小
compare:(a:any, b:any)=>a.numThreads-b.numThreads,
multiple:4,//优先级4
}, },
}, },
{ {
title: t('views.tool.ps.cpuPercent'), title: t('views.tool.ps.cpuPercent'),
dataIndex: 'cpuPercent', dataIndex: 'cpuPercent',
align: 'center', align: 'left',
width: 100, width: 120,
sorter: { sorter: {
compare:(a:any, b:any) => {//字符串转数字比较 compare: (a: any, b: any) => a.cpuPercent - b.cpuPercent,
const parseRate =(rate:string):number => parseFloat(rate.replace('%','')) multiple: 3,
return parseRate(a.cpuPercent) - parseRate(b.cpuPercent);
}, },
multiple:1,//优先级1 customRender(opt) {
return `${opt.value} %`;
}, },
}, },
{ {
title: t('views.tool.ps.diskRead'), title: t('views.tool.ps.diskRead'),
dataIndex: 'diskRead', dataIndex: 'diskRead',
align: 'center', align: 'right',
width: 100, width: 100,
sorter: { sorter: {
compare:(a:any, b:any) => { compare: (a: any, b: any) => a.diskRead - b.diskRead,
const parseRate =(rate:string):number =>{//字符串转数字比较 multiple: 3,
const value = parseFloat(rate);//转化为同单位
if (rate.includes('GB')) return value * 1024; // GB转换为MB
if (rate.includes('MB')) return value; // 保持为 MB
if (rate.includes('KB')) return value / 1024; // KB转换为MB
return 0;
}
return parseRate(a.diskRead) - parseRate(b.diskRead);
}, },
multiple:2,//优先级 customRender(opt) {
return parseSizeFromFile(+opt.value);
}, },
}, },
{ {
title: t('views.tool.ps.diskWrite'), title: t('views.tool.ps.diskWrite'),
dataIndex: 'diskWrite', dataIndex: 'diskWrite',
align: 'center', align: 'right',
width: 100, width: 100,
sorter: { sorter: {
compare:(a:any, b:any) => { compare: (a: any, b: any) => a.diskWrite - b.diskWrite,
const parseRate =(rate:string):number =>{//字符串转数字比较
const value = parseFloat(rate);//转化为同单位
if (rate.includes('GB')) return value * 1024; // GB转换为MB
if (rate.includes('MB')) return value; // 保持为 MB
if (rate.includes('KB')) return value / 1024; // KB转换为MB
return 0;
}
return parseRate(a.diskWrite) - parseRate(b.diskWrite);
},
multiple: 3, multiple: 3,
}, },
customRender(opt) {
return parseSizeFromFile(+opt.value);
},
},
{
title: t('views.tool.ps.numThreads'),
dataIndex: 'numThreads',
align: 'left',
width: 100,
sorter: {
//线程数比较大小
compare: (a: any, b: any) => a.numThreads - b.numThreads,
multiple: 4, //优先级4
},
},
{
title: t('views.tool.ps.runTime'),
dataIndex: 'startTime',
align: 'left',
width: 100,
customRender(opt) {
const second = diffValue(Date.now(), +opt.value, 'second');
return parseDuration(second);
},
},
{
title: t('views.tool.ps.username'),
dataIndex: 'username',
align: 'left',
width: 100,
},
{
title: t('views.tool.ps.name'),
dataIndex: 'name',
align: 'left',
}, },
]; ];
/**表格分页器参数 */
let tablePagination = reactive({
/**当前页数 */
current: 1,
/**每页条数 */
pageSize: 20,
/**默认的每页条数 */
defaultPageSize: 20,
/**指定每页可以显示多少条 */
pageSizeOptions: ['10', '20', '50', '100'],
/**只有一页时是否隐藏分页器 */
hideOnSinglePage: false,
/**是否可以快速跳转至某页 */
showQuickJumper: true,
/**是否可以改变 pageSize */
showSizeChanger: true,
/**数据总数 */
total: 0,
showTotal: (total: number) => t('common.tablePaginationTotal', { total }),
onChange: (page: number, pageSize: number) => {
tablePagination.current = page;
tablePagination.pageSize = pageSize;
},
});
/**钩子函数,界面打开初始化*/
onMounted(() => {
fnRealTime(false);
});
/**钩子函数,界面关闭*/
onBeforeUnmount(() => {
ws.close();
});
</script> </script>
<template> <template>
<PageContainer> <PageContainer>
<a-card <a-card
:bordered="false" :bordered="false"
:body-style="{ marginBottom: '24px', paddingBottom: 0 }" :body-style="{ marginBottom: '24px', paddingBottom: 0 }"
> >
<a-form :model="queryParams" name="formParams" layout="horizontal"> <!-- 表格搜索栏 -->
<a-form :model="queryParams" name="queryParams" layout="horizontal">
<a-row :gutter="16"> <a-row :gutter="16">
<a-col :lg="3" :md="6" :xs="12"> <a-col :lg="4" :md="6" :xs="12">
<a-form-item :label="t('views.tool.ps.changeTime')" name="changeTime"> <a-form-item :label="t('views.tool.ps.pid')" name="pid">
<a-select
v-model:value="queryParams.changeTime"
:options="timeOptions"
:placeholder="t('common.selectPlease')"
@change='fnRealTime2'
/>
</a-form-item></a-col>
<a-col :lg="3" :md="6" :xs="12">
<a-form-item :label="t('views.tool.ps.PID')" name="PID">
<a-input-number <a-input-number
v-model:value="queryParams.pid" v-model:value="queryParams.pid"
allow-clear allow-clear
:placeholder="t('common.inputPlease')" :placeholder="t('common.inputPlease')"
style='width: 100%' style="width: 100%"
></a-input-number> ></a-input-number>
</a-form-item></a-col> </a-form-item>
</a-col>
<a-col :lg="6" :md="12" :xs="24"> <a-col :lg="6" :md="12" :xs="24">
<a-form-item :label="t('views.tool.ps.name')" name="name"> <a-form-item :label="t('views.tool.ps.name')" name="name">
<a-input <a-input
@@ -304,7 +293,8 @@ const tableColumns: ColumnsType<any> = [
allow-clear allow-clear
:placeholder="t('common.inputPlease')" :placeholder="t('common.inputPlease')"
></a-input> ></a-input>
</a-form-item></a-col> </a-form-item>
</a-col>
<a-col :lg="6" :md="12" :xs="24"> <a-col :lg="6" :md="12" :xs="24">
<a-form-item :label="t('views.tool.ps.username')" name="username"> <a-form-item :label="t('views.tool.ps.username')" name="username">
<a-input <a-input
@@ -312,35 +302,64 @@ const tableColumns: ColumnsType<any> = [
allow-clear allow-clear
:placeholder="t('common.inputPlease')" :placeholder="t('common.inputPlease')"
></a-input> ></a-input>
</a-form-item></a-col> </a-form-item>
<a-col :lg="3" :md="4" :xs="5"> </a-col>
<a-col :lg="4" :md="12" :xs="24">
<a-form-item> <a-form-item>
<a-button type="primary" @click='queryTime()'> <a-space :size="8">
<a-button type="primary" @click.prevent="fnQuery()">
<template #icon><SearchOutlined /></template> <template #icon><SearchOutlined /></template>
{{ t('common.search') }} {{ t('common.search') }}
</a-button> </a-button>
<a-button type="default" @click.prevent="queryReset()" style='left: 20px;'> <a-button type="default" @click.prevent="fnQueryReset">
<template #icon><ClearOutlined /></template> <template #icon><ClearOutlined /></template>
{{ t('common.reset') }} {{ t('common.reset') }}
</a-button> </a-button>
</a-space>
</a-form-item> </a-form-item>
</a-col> </a-col>
</a-row> </a-row>
</a-form> </a-form>
<div>{{ state.query }}</div>
<div>{{ queryParams }}</div>
</a-card> </a-card>
<a-card :bordered="false" :body-style="{ padding: '0px' }">
<!-- 插槽-卡片左侧侧 -->
<template #title>
<a-form layout="inline">
<a-form-item :label="t('views.tool.ps.realTime')" name="realTime">
<a-select
v-model:value="state.intervalTime"
:options="[
{ label: t('views.tool.ps.realTimeHigh'), value: 3_000 },
{ label: t('views.tool.ps.realTimeRegular'), value: 5_000 },
{ label: t('views.tool.ps.realTimeLow'), value: 10_000 },
{ label: t('views.tool.ps.realTimeStop'), value: -1 },
]"
:placeholder="t('common.selectPlease')"
@change="fnIntervalChange"
style="width: 100px"
/>
</a-form-item>
</a-form>
</template>
<!-- 表格列表 -->
<a-table <a-table
class="table" class="table"
row-key="id" row-key="pid"
:columns="tableColumns" :columns="tableColumns"
:pagination="tablePagination"
:loading="tableState.loading" :loading="tableState.loading"
:data-source="tableState.data" :data-source="tableState.data"
:size="tableState.size" size="small"
:scroll="{ y: 'calc(100vh - 480px)' }" :scroll="{ x: tableColumns.length * 120 }"
:pagination='false'
></a-table> ></a-table>
</a-card>
</PageContainer> </PageContainer>
</template> </template>
<style lang="less" scoped> <style lang="less" scoped>
.table :deep(.ant-pagination) { .table :deep(.ant-pagination) {
padding: 0 24px; padding: 0 24px;