简单模拟K8S实时更新pod发送json消息
mock一下pod数据
package models
type PodModel struct {
PodName string
PodImage string
PodNode string
}
func MockPodList() []*PodModel {
return []*PodModel{
{PodName: "pod-101", PodImage: "nginx:1.18", PodNode: "node1"},
{PodName: "pod-76xs", PodImage: "alpine:3.12", PodNode: "node2"},
{PodName: "pod-F#ff3", PodImage: "tomcat:8", PodNode: "node3"},
}
}
实现发送json数据
// SendAllPods 向所有客户端发送pod信息
func (c *ClientMapStruct) SendAllPods() {
c.data.Range(func(key, value interface{}) bool {
conn := value.(*WsClient).conn
//err := conn.WriteMessage(websocket.TextMessage, []byte(msg))
err := conn.WriteJSON(models.MockPodList())
if err != nil {
c.Remove(conn)
log.Println(err)
}
return true
})
}
<template>
<div>
<div style="width: 95%;margin: 0 auto">
<div style="width: 95%;margin:30px auto">
<el-table
:data="podList"
border
style="width: 100%">
<el-table-column
prop="PodName"
label="PodName"
width="100">
</el-table-column>
<el-table-column
prop="PodImage"
label="Pod镜像"
width="220">
</el-table-column>
<el-table-column
prop="PodNode"
label="Pod节点"
width="100">
</el-table-column>
</el-table>
</div>
</div>
</div>
</template>
<script type="module">
module.exports = {
data() {
return {
podList: [],
}
},
created() {
NewClient().onmessage = (e) => {
if (e.data !== 'ping') {
this.podList = JSON.parse(e.data)
// 强制刷新
this.$forceUpdate()
}
}
},
}
</script>
<style>
.sdt {
margin: 10px auto;
width: 90%;
border-radius: 5px;
display: block;
float: left;
margin-left: 50px
}
.sdt dt {
width: 100%;
display: block;
color: #3A7B43;
font-size: 16px;
font-weight: bold;
margin-bottom: 10px
}
.sdt dd {
float: left;
margin: 0 auto;
text-indent: 1em
}
.sdt .row {
width: 100%;
}
.sdt dd .search {
width: 50%;
}
.sdt dd a {
color: #3a8ee6
}
.sdt dd a:hover {
background: #eb5975;
color: #fff
}
.sdt dd .select {
background: #eb5975;
color: #fff
}
.sdt dd .numtext {
width: 100px
}
.sdt dd span {
margin: 0 auto
}
a {
cursor: pointer
}
.el-pagination {
margin: 0 auto;
float: left
}
</style>
const NewClient=function () {
var ws = new WebSocket("ws://localhost:8080/echo");
ws.onopen = function(){
console.log("open");
}
ws.onclose = function(e){
console.log("close");
}
ws.onerror = function(e){
console.log(e);
}
return ws
}