websocket实现后台向前端推送数据

springboot +websocket+vue

贴入配置

/**
 * @author zhangzhang
 */
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketStompConfig implements WebSocketMessageBrokerConfigurer {

    /**
     * 注册stomp端点
     * @param registry
     */
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {

        // 允许使用socketJs方式访问 即可通过http://IP:PORT/admin/ws来和服务端websocket连接
        registry.addEndpoint("/admin/ws").setAllowedOrigins("*").withSockJS();
    }

    /**
     * 配置信息代理
     * @param registry
     */
    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {

        // 订阅Broker名称 user点对点 topic广播即群发
        registry.enableSimpleBroker("/user","/topic");
        // 全局(客户端)使用的消息前缀
        registry.setApplicationDestinationPrefixes("/app");
        // 点对点使用的前缀 无需配置 默认/user
        registry.setUserDestinationPrefix("/user");
    }
}

后台推送数据的代码(此处为定时任务推送)

	@Autowired
    private SimpMessagingTemplate messagingTemplate;
    
	@Async
	@Scheduled(initialDelay = 1000,fixedRate = 5000)//启动后1秒执行没5秒执行一次
	 public void push() {
		try {
			messagingTemplate.convertAndSend("/topic/checkLogTotal", Long.valueOf(checkLogTotal==null ? "0" : checkLogTotal));
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	 }

前端vue代码

mounted() {
        if ('WebSocket' in window) {
            this.initWebSocket()
            // this.connectSrv();
        } else {
            console.log('当前浏览器 Not support websocket')
        }
}
initWebSocket () {
            this.connection()
        },
        connection () {
            let self = this
            // 'http://**********ip:8082/admin/ws'
            const socket = new SockJS('http://**********ip:8082/admin/ws')
            self.stompClient = Stomp.over(socket)
            self.stompClient.connect({}, (frame) => {
                self.stompClient.subscribe('/topic/checkLogTotal', (greeting) => {
                    self.next = JSON.parse(greeting.body)
                    self.autoAddSumDemo()
                })
            })
        },
  • 6
    点赞
  • 33
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值