最近要做一个消息推送的功能,第一个想到了webscoket,使用场景是这样的,有一个平台,每次平台更新有新功能就会推送到购买平台的机构上。大致就是这样一个使用场景。下面是代码部分。
config
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
controller 两个接口 ,一个是添加人员,一个是获取当前人员 都是测试的,可以根据自己的业务实际更改
import com.ghc.demo07.entity.UserTest;
import com.ghc.demo07.service.WebSocketServer;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
@CrossOrigin
public class TestController {
@RequestMapping(value = "/pushVideoListToWeb", method = RequestMethod.POST, consumes = "application/json")
public @ResponseBody Map<String, Object> pushVideoListToWeb(@RequestBody Map<String, Object> param) {
Map<String, Object> result = new HashMap<>();
try {
WebSocketServer.sendInfo("有新客户呼入,sltAccountId:" + param.get("sltAccountId").toString());
result.put("operationResult", true);
} catch (IOException e) {
result.put("operationResult", true);
}
return result;
}
@GetMapping("/getList")
public List<UserTest> getList(Map<String, Object> param) {
List<UserTest> list = new ArrayList<>();
UserTest user = new UserTest();
user.setName("ghc");
user.setMailbox("759805506@qq.com");
list.add(user);
user = new UserTest();
user.setName("ghc1");
user.setMailbox("1070195224@qq.com");
list.add(user);
return list;
}
}
entity 这个可以不要,就是一个实体类
public class UserTest {
private String name;
private String mailbox;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMailbox() {
return mailbox;
}
public void setMailbox(String mailbox) {
this.mailbox = mailbox;
}
}
WebSocketServer 服务类,可以用在线测试工具,连接是否连接上,连接成功会返回前台相应提示,可以根据自己的业务实际定义
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;
@Slf4j
@ServerEndpoint(value = "/websocket")
@Component
public class WebSocketServer {
//静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
private static int onlineCount = 0;
//concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();
//与某个客户端的连接会话,需要通过它来给客户端发送数据
private Session session;
/**
* 连接建立成功调用的方法*/
@OnOpen
public void onOpen(Session session) {
this.session = session;
webSocketSet.add(this); //加入set中
addOnlineCount(); //在线数加1
log.info("有新连接加入!当前在线人数为" + getOnlineCount());
try {
sendMessage("连接成功");
} catch (IOException e) {
log.error("websocket IO异常");
}
}
/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose() {
webSocketSet.remove(this); //从set中删除
subOnlineCount(); //在线数减1
log.info("有一连接关闭!当前在线人数为" + getOnlineCount());
}
/**
* 收到客户端消息后调用的方法
*
* @param message 客户端发送过来的消息*/
@OnMessage
public void onMessage(String message, Session session) {
log.info("来自客户端的消息:" + message);
//群发消息
for (WebSocketServer item : webSocketSet) {
try {
item.sendMessage(message);
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
*
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error) {
log.error("发生错误");
error.printStackTrace();
}
public void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
}
/**
* 群发自定义消息
* */
public static void sendInfo(String message) throws IOException {
log.info(message);
for (WebSocketServer item : webSocketSet) {
try {
item.sendMessage(message);
} catch (IOException e) {
continue;
}
}
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
WebSocketServer.onlineCount++;
}
public static synchronized void subOnlineCount() {
WebSocketServer.onlineCount--;
}
}
前台 也是根据自己的业务 实际定义
<template>
<div class="hello">{{msg}}</div>
</template>
<script>
export default {
name: "websocket",
data() {
return {
msg: "",
}
},
mounted() {
this.init()
},
methods: {
init() {
let _this = this
let socket
console.log(typeof socket)
if (typeof WebSocket == "undefined") {
console.log("您的浏览器不支持WebSocket")
} else {
console.log("您的浏览器支持WebSocket")
socket = new WebSocket("ws://localhost:8080/websocket")
socket.onopen = function () {
console.log("Socket 已打开")
}
//获得消息事件
socket.onmessage = function (msg) {
_this.msg = ""
_this.msg += msg.data
//发现消息进入 调后台获取
_this.$axios
.get("/getList")
.then((res) => {
console.log("res")
console.log(res)
res.forEach((item) => {
_this.msg += "\n" + item.name
})
})
.catch((error) => {
console.log("error")
console.log(error)
})
}
//关闭事件
socket.onclose = function () {
console.log("Socket已关闭")
}
//发生了错误事件
socket.onerror = function () {
alert("Socket发生了错误")
}
}
},
},
}
</script>
在线测试地址:“http://coolaf.com/tool/chattest”
上面基于自己的测试,可以根据自己的需求实际定义。如果对你有帮助还请点赞。