目前在我的应用程序中,每隔10秒使用弹簧websockets播放一条消息。这是在我的spring应用程序中向用户广播消息的方式。
@Configuration
@EnableWebSocketMessageBroker
@EnableScheduling
@Component
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Autowired
private SimpMessagingTemplate template;
private TaskScheduler scheduler = new ConcurrentTaskScheduler();
public WebSocketConfig() {
System.out.printf(" ---INIT----------");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/simplemessages").withSockJS();
}
// @Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic/", "/queue/");
config.setApplicationDestinationPrefixes("/app");
}
@PostConstruct
private void broadcastTimePeriodically() {
scheduler.scheduleAtFixedRate(new Runnable() {
public void run() {
try{
template.convertAndSend("/topic/simplemessagesresponse", "{shares:true,price:100.00}");
}catch(MessagingException e){
System.err.println("!!!!!! websocket timer error :>"+e.toString());
}
}
}, 10000);
}
@PreDestroy
private void destroyServices(){
}
// @Override
public void configureClientInboundChannel(ChannelRegistration registration) {
}
// @Override
public void configureClientOutboundChannel(ChannelRegistration registration) {
registration.taskExecutor().corePoolSize(4).maxPoolSize(10);
}
//@Override
public boolean configureMessageConverters(List<MessageConverter> arg0) {
// TODO Auto-generated method stub
return true;
}
@Override
public void configureWebSocketTransport(WebSocketTransportRegistration arg0) {
// TODO Auto-generated method stub
}
}
这是浏览器收到的方式,
var socket = new SockJS(desz);
stompClient = Stomp.over(socket);
stompClient.connect('user', 'guest', function(frame) {
stompClient.subscribe("/topic/simplemessagesresponse", function(servermessage) {
var stompResponse = JSON.parse((servermessage.body));
console.log('server msg: '+stompResponse);
});
});
我想向某些用户广播相同的消息,而另一组用户定期发送另一条消息。我应该如何修改上面的代码才能实现这个目标?
答案 0 :(得分:0)
您可以在调度程序run()方法中使用此方法
this.simpMessagingTemplate.convertAndSend("/queue/" + userGroup.geName(),
messageMap.get(userGroup.geName()));
在客户端,您可以订阅特定的网址&#34; queue / {groupName}&#34;
stompClient.subscribe("/queue/${groupName}", function(servermessage) {
var stompResponse = JSON.parse((servermessage.body));
console.log('server msg: '+stompResponse);
});
注意:(在客户端示例变量&#39; groupName&#39;被发送到控制器查看并在JSP中使用EL访问)