springboot+websocket 实现简单的订阅广播,定时推送消息

1.加入依赖

<!--websocket-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>

2.加入websocket配置文件


import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfiguration implements WebSocketMessageBrokerConfigurer {

    /**
     * 注册stomp端点,主要是起到连接作用
     * @param stompEndpointRegistry
     */
    @Override
    public void registerStompEndpoints(StompEndpointRegistry stompEndpointRegistry) {
        stompEndpointRegistry
                .addEndpoint("/webSocket")  //端点名称
                //.setHandshakeHandler() 握手处理,主要是连接的时候认证获取其他数据验证等
                //.addInterceptors() 拦截处理,和http拦截类似
                .setAllowedOrigins("*"); //跨域
//                .withSockJS(); //使用sockJS

    }

    /**
     * 注册相关服务
     * @param registry
     */
    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        //这里使用的是内存模式,生产环境可以使用rabbitmq或者其他mq。
        //这里注册两个,主要是目的是将广播和队列分开。
        //registry.enableStompBrokerRelay().setRelayHost().setRelayPort() 其他方式
        registry.enableSimpleBroker("/topic", "/queue");
        //客户端名称前缀
        registry.setApplicationDestinationPrefixes("/app");
        //用户名称前
        registry.setUserDestinationPrefix("/user");
    }
}

3.定时任务,五秒推送一次

import com.alibaba.fastjson.JSONObject;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;


@EnableScheduling
@Component

public class SendAlarm {

    @Resource
    private SimpMessagingTemplate simpMessagingTemplate;
    

    @Scheduled(cron = "0/5 * * * * ?")
    public void start() {
        RequestMsg requestMsg = new RequestMsg();
        requestMsg.setBody(LocalDateTime.now().format(DateTimeFormatter.ofPattern("YYYY-MM-dd HH:mm:ss")));
        String jsonString = JSONObject.toJSONString(requestMsg);
        simpMessagingTemplate.convertAndSend("/topic/companyName/alarm",jsonString);
    }
}

4.js:

var stomp = null;
var url = "ws://10.1.1.81:8085/webSocket";
        stomp = Stomp.client(url);
        //连接
        stomp.connect({}, function (frame) {
            //订阅广播
            stomp.subscribe("/topic/default/alarm", function (res) {
                console.log(res.body)
            });
        });

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值