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

 

  • 0
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 7
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值