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

View File

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

View File

@@ -1,346 +1,365 @@
<script setup lang="ts">
import { reactive ,toRaw, onMounted } from 'vue';
import { reactive, onMounted, onBeforeUnmount, nextTick } from 'vue';
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 { OptionsType, WS } from '@/plugins/ws-websocket';
import {
RESULT_CODE_ERROR
} from '@/constants/result-constants';
import { RESULT_CODE_ERROR } from '@/constants/result-constants';
import { diffValue, parseDuration } from '@/utils/date-utils';
import { parseSizeFromFile } from '@/utils/parse-utils';
const { t } = useI18n();
const ws = new WS();
//查询数据
/**表单查询参数 */
let queryParams = reactive({
pid: undefined,
name:"",
username:"",
flag: false,
changeTime:5000,
name: '',
username: '',
});
//临时缓存
let queryParams2 = reactive({
pid: undefined,
name:"",
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)//设置定时器
/**状态对象 */
let state = reactive({
/**调度器 */
interval: null as any,
/**刷新周期 */
intervalTime: 5_000,
/**查询参数 */
query: {
pid: undefined,
name: '',
username: '',
},
});
/**查询按钮**/
function queryTime(){//将表单中的数据传递给缓存数据(缓存数据自动同步请求信息中)
queryParams2.pid=queryParams.pid;
queryParams2.username=queryParams.username;
queryParams2.name=queryParams.name;
//queryParams.flag = true
queryParams2.flag=true
queryParams.pid=undefined;
queryParams.name="";
queryParams.username="";
}
/**重置按钮**/
function queryReset(){
queryParams.flag = false
queryParams2.flag = false
}
let s:any = null
/**定时器**/
function queryReset2(c:boolean){
if(c){
clearInterval(s)//清理旧定时器
ws.close();//断开原来的wb连接
fnRealTime();//建立新的实时数据连接
}
s = setInterval(()=>{//设置新的定时器s
extracted();
},queryParams.changeTime)
}
/**刷新频率改变**/
function fnRealTime2() {//时间粒度改变时触发
queryReset2(true)//改变定时器
}
/**
* 实时数据
*/
function fnRealTime() {
const options: OptionsType = {
url: '/ws',
onmessage: wsMessage,
onerror: wsError,
};
//建立连接
ws.connect(options);
}
/**接收数据后回调(失败) */
function wsError(ev: any) {
// 接收数据后回调
console.error(ev);
}
/**接收数据后回调(成功) */
function wsMessage(res: Record<string, any>) {
const { code, requestId, data } = res;//获取数据
const { code, requestId, data } = res;
if (code === RESULT_CODE_ERROR) {
console.warn(res.msg);
return;
}
// 处理 data.startTime转换成运行时间并赋值到新的数组processedData
let processedData: any;
if (Array.isArray(data)) {
processedData = data.map(item => {
if (item.startTime) {//startTime有值
return { ...item, runTime: calculateRunTime(item.startTime) };
}
return item;
// 建联时发送请求
if (!requestId && data.clientId) {
fnGetList();
return;
}
// 收到消息数据
if (requestId.startsWith('ps_')) {
// 将数据填入表格
if (Array.isArray(data)) {
tableState.data = data;
} else {
tableState.data = [];
}
}
}
/**实时数据*/
function fnRealTime(reLink: boolean) {
if (reLink) {
ws.close();
}
const options: OptionsType = {
url: '/ws',
onmessage: wsMessage,
onerror: (ev: any) => {
// 接收数据后回调
console.error(ev);
},
};
//建立连接
ws.connect(options);
}
/**调度器周期变更*/
function fnIntervalChange(v: any) {
clearInterval(state.interval);
const timer = parseInt(v);
if (timer > 1_000) {
state.intervalTime = v;
fnGetList();
}
}
/**查询列表 */
function fnGetList() {
if (tableState.loading || ws.state() === -1) return;
tableState.loading = true;
const msg = {
requestId: `ps_${state.interval}`,
type: 'ps',
data: state.query,
};
// 首发
ws.send(msg);
// 定时刷新数据
state.interval = setInterval(() => {
msg.data = state.query;
ws.send(msg);
}, state.intervalTime);
tableState.loading = false;
}
/**查询参数传入 */
function fnQuery() {
state.query = JSON.parse(JSON.stringify(queryParams));
nextTick(() => {
ws.send({
requestId: `ps_${state.interval}`,
type: 'ps',
data: state.query,
});
} else if (data && data.startTime) {
processedData = { ...data, runTime: calculateRunTime(data.startTime) };
} else {
processedData = data; // 如果没有 startTime则不做处理
}
if (requestId) {
tableState.data = processedData; // 将数据填入表格
}
}
/**处理开始时间**/
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({
'requestId': 'dxxx',
'type': 'ps',
'data': data,
});
}
/**表格状态 */
let tableState: TableStateType = reactive({
loading: false,
size: 'large',
data: [],
});
/**查询参数重置 */
function fnQueryReset() {
Object.assign(queryParams, {
pid: undefined,
name: '',
username: '',
});
tablePagination.current = 1;
tablePagination.pageSize = 20;
// 重置查询条件
Object.assign(state.query, {
pid: undefined,
name: '',
username: '',
});
}
/**表格状态类型 */
type TableStateType = {
/**加载等待 */
loading: boolean;
/**紧凑型 */
size: SizeType;
/**记录数据 */
data: object[];
};
/**表格状态 */
let tableState: TableStateType = reactive({
loading: false,
data: [],
});
/**表格字段列 */
const tableColumns: ColumnsType<any> = [
{
title: t('views.tool.ps.PID'),
dataIndex: 'PID',
align: 'center',
width: 50,
sorter:{//PID排序
compare:(a:any, b:any)=>a.PID-b.PID,
multiple:3,
}
},
{
title: t('views.tool.ps.name'),
dataIndex: 'name',
align: 'center',
title: t('views.tool.ps.pid'),
dataIndex: 'pid',
align: 'right',
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
sorter: {
compare: (a: any, b: any) => a.pid - b.pid,
multiple: 3,
},
},
{
title: t('views.tool.ps.cpuPercent'),
dataIndex: 'cpuPercent',
align: 'center',
width: 100,
sorter:{
compare:(a:any, b:any) => {//字符串转数字比较
const parseRate =(rate:string):number => parseFloat(rate.replace('%',''))
return parseRate(a.cpuPercent) - parseRate(b.cpuPercent);
},
multiple:1,//优先级1
align: 'left',
width: 120,
sorter: {
compare: (a: any, b: any) => a.cpuPercent - b.cpuPercent,
multiple: 3,
},
customRender(opt) {
return `${opt.value} %`;
},
},
{
title: t('views.tool.ps.diskRead'),
dataIndex: 'diskRead',
align: 'center',
align: 'right',
width: 100,
sorter:{
compare:(a:any, b:any) => {
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.diskRead) - parseRate(b.diskRead);
},
multiple:2,//优先级
sorter: {
compare: (a: any, b: any) => a.diskRead - b.diskRead,
multiple: 3,
},
customRender(opt) {
return parseSizeFromFile(+opt.value);
},
},
{
title: t('views.tool.ps.diskWrite'),
dataIndex: 'diskWrite',
align: 'center',
align: 'right',
width: 100,
sorter:{
compare:(a:any, b:any) => {
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,
sorter: {
compare: (a: any, b: any) => a.diskWrite - b.diskWrite,
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>
<template>
<PageContainer>
<a-card
:bordered="false"
: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-col :lg="3" :md="6" :xs="12">
<a-form-item :label="t('views.tool.ps.changeTime')" name="changeTime">
<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-col :lg="4" :md="6" :xs="12">
<a-form-item :label="t('views.tool.ps.pid')" name="pid">
<a-input-number
v-model:value="queryParams.pid"
allow-clear
:placeholder="t('common.inputPlease')"
style='width: 100%'
style="width: 100%"
></a-input-number>
</a-form-item></a-col>
<a-col :lg="6" :md="12" :xs="24">
<a-form-item :label="t('views.tool.ps.name')" name="name">
</a-form-item>
</a-col>
<a-col :lg="6" :md="12" :xs="24">
<a-form-item :label="t('views.tool.ps.name')" name="name">
<a-input
v-model:value="queryParams.name"
allow-clear
:placeholder="t('common.inputPlease')"
></a-input>
</a-form-item></a-col>
<a-col :lg="6" :md="12" :xs="24">
<a-form-item :label="t('views.tool.ps.username')" name="username">
v-model:value="queryParams.name"
allow-clear
:placeholder="t('common.inputPlease')"
></a-input>
</a-form-item>
</a-col>
<a-col :lg="6" :md="12" :xs="24">
<a-form-item :label="t('views.tool.ps.username')" name="username">
<a-input
v-model:value="queryParams.username"
allow-clear
:placeholder="t('common.inputPlease')"
></a-input>
</a-form-item></a-col>
<a-col :lg="3" :md="4" :xs="5">
<a-form-item>
<a-button type="primary" @click='queryTime()'>
<template #icon><SearchOutlined /></template>
{{ t('common.search') }}
</a-button>
<a-button type="default" @click.prevent="queryReset()" style='left: 20px;'>
<template #icon><ClearOutlined /></template>
{{ t('common.reset') }}
</a-button>
</a-form-item>
</a-col>
<a-col :lg="4" :md="12" :xs="24">
<a-form-item>
<a-space :size="8">
<a-button type="primary" @click.prevent="fnQuery()">
<template #icon><SearchOutlined /></template>
{{ t('common.search') }}
</a-button>
<a-button type="default" @click.prevent="fnQueryReset">
<template #icon><ClearOutlined /></template>
{{ t('common.reset') }}
</a-button>
</a-space>
</a-form-item>
</a-col>
</a-row>
</a-form>
<div>{{ state.query }}</div>
<div>{{ queryParams }}</div>
</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
class="table"
row-key="pid"
:columns="tableColumns"
:pagination="tablePagination"
:loading="tableState.loading"
:data-source="tableState.data"
size="small"
:scroll="{ x: tableColumns.length * 120 }"
></a-table>
</a-card>
<a-table
class="table"
row-key="id"
:columns="tableColumns"
:loading="tableState.loading"
:data-source="tableState.data"
:size="tableState.size"
:scroll="{ y: 'calc(100vh - 480px)' }"
:pagination='false'
></a-table>
</PageContainer>
</template>
<style lang="less" scoped>
.table :deep(.ant-pagination) {
padding: 0 24px;