Springboot+VUE 基于socket实现数据实时刷新
一、pom.xml加入依赖<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-websocket</artifactId></...
一、pom.xml加入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
二、注入ServerEndpointExporter
@Configuration
public class WebSocketConfig
{
/**
* 注入ServerEndpointExporter,
* 这个bean会自动注册使用了@ServerEndpoint注解声明的Websocket endpoint
*/
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
三、发布socket服务
@Component
@ServerEndpoint("/websocket/{shopId}")
public class WebSocket
{
private Session session;
private static CopyOnWriteArraySet<WebSocket> webSockets = new CopyOnWriteArraySet();
private static Map<String,Session> sessionPool = new HashMap<String,Session>();
@OnOpen
public void onOpen(Session session, @PathParam(value="shopId")String shopId) {
this.session = session;
webSockets.add(this);
sessionPool.put(shopId, session);
System.out.println("【websocket消息】有新的连接,总数为:"+webSockets.size());
}
@OnClose
public void onClose() {
webSockets.remove(this);
System.out.println("【websocket消息】连接断开,总数为:"+webSockets.size());
}
@OnMessage
public void onMessage(String message) {
System.out.println("【websocket消息】收到客户端消息:"+message);
}
// 此为广播消息
public void sendAllMessage(String message) {
for(WebSocket webSocket : webSockets) {
System.out.println("【websocket消息】广播消息:"+message);
try {
webSocket.session.getAsyncRemote().sendText(message);
} catch (Exception e) {
e.printStackTrace();
}
}
}
// 此为单点消息
public void sendOneMessage(String shopId, String message) {
Session session = sessionPool.get(shopId);
if (session != null) {
try {
session.getAsyncRemote().sendText(message);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
四、实现实时刷新的二种方式,前端定时刷新就不提了:
1)通知方式
当数据变化时,可通过调用http服务(controller调用了webSocket方法)通知页面socket客户端更新数据;
@RestController
@RequestMapping("socket")
public class SocketController
{
@Autowired
private WebSocket webSocket;
@RequestMapping("/sendAllWebSocket")
public String test() {
webSocket.sendAllMessage("{\"data\":\"清晨起来打开窗,心情美美哒~\"}");
return "websocket群体发送!";
}
@RequestMapping("/sendOneWebSocket")
public String sendOneWebSocket() {
webSocket.sendOneMessage("DPS007", "{\"data\":\"只要你乖给你买条gai!\"}");
return "websocket单人发送";
}
}
2)后台轮训方式:后台启动定时任务,看数据是否变化(可获取数据最新id比较),然后再通过调用webSocket通知页面客户端刷新数据;
@EnableScheduling 定时计划执行方法
更多推荐
所有评论(0)