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

发布于:2021-06-14 16:28:25

1.加入依赖




org.springframework.boot
spring-boot-starter-websocket

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)
});
});

?

相关推荐

最新更新

猜你喜欢