springboot+websocket 后台主动向前端推送消息
最近做项目,用到后台需要实时向前台推送消息,看了很多例子,终于实现
idea工具,创建maven项目(这里就不多说了,可以直接用骨架搭建)
首先创建 WebSocketConfig 搭建websocket服务器
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
//消息主动推送
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/socket").withSockJS();
}
//消息主动推送给指定用户
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.enableSimpleBroker("/server","/user");
}
}
前端index.html页面,需要引入三个jar报,可以在https://www.bootcdn.cn/下载
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="jquery.js"></script>
<script src="sockjs.js"></script>
<script src="stomp.js"></script>
</head>
<body>
<div id="msg"></div>
<script>
var sockJS=new SockJS("http://localhost:8080/socket");
var stompClient=Stomp.over(sockJS);
stompClient.connect({},function(data){
//订阅
stompClient.subscribe("/server/sendMessageByServer",function (response) {
$("#msg").append(response.body+"<br/>");
})
})
</script>
</body>
</html>
推送指定user.html用户页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="jquery.js"></script>
<script src="sockjs.js"></script>
<script src="stomp.js"></script>
</head>
<body>
${id}
<div id="msg"></div>
<script>
var id='${id}';
var sockJS=new SockJS("http://localhost:8080/socket");
var stompClient=Stomp.over(sockJS);
stompClient.connect({},function(data){
//订阅
stompClient.subscribe("/user/"+id+"/server/sendMessageByServer",function (response) {
$("#msg").append(response.body+"<br/>");
})
})
</script>
</body>
</html>
controller实体类
@Controller
@RequestMapping
public class IndexController {
@GetMapping("/")
public String index(){
return "index";
}
//发送指定用户
@GetMapping("/user")
public String user(Long id, ModelMap model){
model.addAttribute("id",id);
return "user";
}
}
MyJob类
@Configuration
public class MyJob {
@Autowired
private SimpMessagingTemplate simpMessagingTemplate;
@Scheduled(fixedRate = 1000)
public void sendMessage(){
System.out.println("来自服务端的消息");
simpMessagingTemplate.convertAndSend("/server/sendMessageByServer",System.currentTimeMillis());
}
@Scheduled(fixedRate = 10000)
public void sendMessageToUser(){
System.out.println("来自服务端的消息,推送给指定用户");
simpMessagingTemplate.convertAndSendToUser("1","/server/sendMessageByServer",System.currentTimeMillis());
}
}
以上是全部代码:
运行springboot启动方法,启动成功后,浏览器访问
http://localhost:8080/ 返回的是每隔1秒获取到的毫秒数
http://localhost:8080/user?id=1 返回的是每隔10秒获取到的毫秒数
这里的id与MyJob类中
simpMessagingTemplate.convertAndSendToUser(“1”,”/server/sendMessageByServer”,System.currentTimeMillis());
的“1”对应,代表id为1的用户
大家可以灵活运用
simpMessagingTemplate.convertAndSend(“/server/sendMessageByServer”,System.currentTimeMillis());
或者
simpMessagingTemplate.convertAndSendToUser(“1”,”/server/sendMessageByServer”,System.currentTimeMillis());
可以放到大家需要推送的方法中
链接:https://pan.baidu.com/s/1p8Etfh3KH6jBrAmfhb-x9Q
提取码:kz8a
还没有评论,来说两句吧...