我有一个Rabbitmq服务器,我在其中使用数据,我想使用websocket将数据发送给特定的连接用户。如果我使用/ topic / message,则所有客户端都会收到该消息,但我想将数据发送给特定用户。 这是客户端:
function connect() {
var socket = new SockJS('/message');
stompClient = Stomp.over(socket);
stompClient.connect({}, function(frame) {
setConnected(true);
console.log('Connected : ' + frame);
stompClient.subscribe('/user/queue/reply', function(msg){
showGreeting(JSON.parse(msg.body).content);
});
});
}
和webSocket配置文件:
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements
WebSocketMessageBrokerConfigurer{
private static final Logger log =
LoggerFactory.getLogger(WebSocketConfig.class);
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config
.setUserDestinationPrefix("/user")
.setApplicationDestinationPrefixes("/app")
.enableSimpleBroker("/topic", "/queue", "/user");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/message").addInterceptors(new
HttpHandshakeInterceptor()).setAllowedOrigins("*").withSockJS();
}
}
和HttpHandshakeInterceptor:
public class HttpHandshakeInterceptor implements HandshakeInterceptor {
@Override
public boolean beforeHandshake(ServerHttpRequest request,
ServerHttpResponse response, WebSocketHandler wsHandler,
Map<String, Object> attributes) throws
Exception {
if (request instanceof ServletServerHttpRequest) {
ServletServerHttpRequest servletRequest =
(ServletServerHttpRequest) request;
HttpSession session =
servletRequest.getServletRequest().getSession();
attributes.put("sessionId", session.getId());
}
return true;
}
}
这是我使用Rabbitmq数据并将其发送给特定用户的控制器:
@RabbitListener(queues="${jsa.rabbitmq.queue}")
public void receivedStatus(byte[] msg) {
String str = new String(msg, StandardCharsets.UTF_8);
JSONParser jsonParser=new JSONParser();
JSONArray clsArray = null;
JSONArray clsRet = new JSONArray();
JSONObject json_data = null;
Object obj;
try {
obj = jsonParser.parse(str);
clsArray = (JSONArray) obj;
for (int i = 0; i < clsArray.size(); i++) {
json_data = (JSONObject) clsArray.get(i);
if((Long)json_data.get("TagKey") == 8 )
{
String tagName = json_data.get("TagName").toString();
Long devKey = (Long) json_data.get("DevKey");
Long tagKey = (Long) json_data.get("TagKey");
String tagVal = (String) json_data.get("Value");
Long tagTime = (Long) json_data.get("Time");
this.clsJ.add(json_data);
}
}
} catch (ParseException e) {
e.printStackTrace();
}
}
和消息映射方法:
@MessageMapping("/message")
public void status(JSONArray ret, SimpMessageHeaderAccessor headerAccessor)
throws Exception {
String sessionId =
headerAccessor.getSessionAttributes().get("sessionId").toString();
messagingTemplate.convertAndSendToUser(sessionId,"/queue/reply",
this.clsJ);
this.clsJ.clear();
}
提前谢谢。