SimpleBrokerMessageHandler.java 15.2 KB
Newer Older
1
/*
R
Rossen Stoyanchev 已提交
2
 * Copyright 2002-2016 the original author or authors.
3 4 5 6 7
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
8
 *      http://www.apache.org/licenses/LICENSE-2.0
9 10 11 12 13 14 15 16
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

17
package org.springframework.messaging.simp.broker;
18

19
import java.security.Principal;
20
import java.util.Collection;
21 22 23
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;
24

25 26
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
27
import org.springframework.messaging.MessageHeaders;
28
import org.springframework.messaging.SubscribableChannel;
29 30
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.SimpMessageType;
31
import org.springframework.messaging.support.MessageBuilder;
32
import org.springframework.messaging.support.MessageHeaderAccessor;
33
import org.springframework.messaging.support.MessageHeaderInitializer;
34
import org.springframework.scheduling.TaskScheduler;
35
import org.springframework.util.Assert;
36
import org.springframework.util.MultiValueMap;
37
import org.springframework.util.PathMatcher;
38 39

/**
40 41 42 43
 * A "simple" message broker that recognizes the message types defined in
 * {@link SimpMessageType}, keeps track of subscriptions with the help of a
 * {@link SubscriptionRegistry} and sends messages to subscribers.
 *
44
 * @author Rossen Stoyanchev
45
 * @author Juergen Hoeller
46 47
 * @since 4.0
 */
48
public class SimpleBrokerMessageHandler extends AbstractBrokerMessageHandler {
49

50 51
	private static final byte[] EMPTY_PAYLOAD = new byte[0];

52
	private final Map<String, SessionInfo> sessions = new ConcurrentHashMap<>();
53

54
	private SubscriptionRegistry subscriptionRegistry;
55

56 57
	private PathMatcher pathMatcher;

58 59
	private Integer cacheLimit;

60 61 62 63 64 65
	private TaskScheduler taskScheduler;

	private long[] heartbeatValue;

	private ScheduledFuture<?> heartbeatFuture;

66 67
	private MessageHeaderInitializer headerInitializer;

68 69

	/**
70 71
	 * Create a SimpleBrokerMessageHandler instance with the given message channels
	 * and destination prefixes.
72 73
	 * @param clientInboundChannel the channel for receiving messages from clients (e.g. WebSocket clients)
	 * @param clientOutboundChannel the channel for sending messages to clients (e.g. WebSocket clients)
74
	 * @param brokerChannel the channel for the application to send messages to the broker
75
	 * @param destinationPrefixes prefixes to use to filter out messages
76
	 */
77
	public SimpleBrokerMessageHandler(SubscribableChannel clientInboundChannel, MessageChannel clientOutboundChannel,
78 79
			SubscribableChannel brokerChannel, Collection<String> destinationPrefixes) {

80 81
		super(clientInboundChannel, clientOutboundChannel, brokerChannel, destinationPrefixes);
		this.subscriptionRegistry = new DefaultSubscriptionRegistry();
82 83 84
	}


85 86 87 88 89 90 91
	/**
	 * Configure a custom SubscriptionRegistry to use for storing subscriptions.
	 * <p><strong>Note</strong> that when a custom PathMatcher is configured via
	 * {@link #setPathMatcher}, if the custom registry is not an instance of
	 * {@link DefaultSubscriptionRegistry}, the provided PathMatcher is not used
	 * and must be configured directly on the custom registry.
	 */
92
	public void setSubscriptionRegistry(SubscriptionRegistry subscriptionRegistry) {
P
Phillip Webb 已提交
93
		Assert.notNull(subscriptionRegistry, "SubscriptionRegistry must not be null");
94
		this.subscriptionRegistry = subscriptionRegistry;
95
		initPathMatcherToUse();
96
		initCacheLimitToUse();
97 98
	}

99 100
	public SubscriptionRegistry getSubscriptionRegistry() {
		return this.subscriptionRegistry;
101 102
	}

103
	/**
104
	 * When configured, the given PathMatcher is passed down to the underlying
105
	 * SubscriptionRegistry to use for matching destination to subscriptions.
106 107 108 109 110
	 * <p>Default is a standard {@link org.springframework.util.AntPathMatcher}.
	 * @since 4.1
	 * @see #setSubscriptionRegistry
	 * @see DefaultSubscriptionRegistry#setPathMatcher
	 * @see org.springframework.util.AntPathMatcher
111 112 113 114 115 116
	 */
	public void setPathMatcher(PathMatcher pathMatcher) {
		this.pathMatcher = pathMatcher;
		initPathMatcherToUse();
	}

117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
	private void initPathMatcherToUse() {
		if (this.pathMatcher != null && this.subscriptionRegistry instanceof DefaultSubscriptionRegistry) {
			((DefaultSubscriptionRegistry) this.subscriptionRegistry).setPathMatcher(this.pathMatcher);
		}
	}

	/**
	 * When configured, the specified cache limit is passed down to the
	 * underlying SubscriptionRegistry, overriding any default there.
	 * <p>With a standard {@link DefaultSubscriptionRegistry}, the default
	 * cache limit is 1024.
	 * @since 4.3.2
	 * @see #setSubscriptionRegistry
	 * @see DefaultSubscriptionRegistry#setCacheLimit
	 * @see DefaultSubscriptionRegistry#DEFAULT_CACHE_LIMIT
	 */
	public void setCacheLimit(Integer cacheLimit) {
		this.cacheLimit = cacheLimit;
		initCacheLimitToUse();
	}

	private void initCacheLimitToUse() {
		if (this.cacheLimit != null && this.subscriptionRegistry instanceof DefaultSubscriptionRegistry) {
			((DefaultSubscriptionRegistry) this.subscriptionRegistry).setCacheLimit(this.cacheLimit);
		}
	}

144 145 146 147 148 149 150 151
	/**
	 * Configure the {@link org.springframework.scheduling.TaskScheduler} to
	 * use for providing heartbeat support. Setting this property also sets the
	 * {@link #setHeartbeatValue heartbeatValue} to "10000, 10000".
	 * <p>By default this is not set.
	 * @since 4.2
	 */
	public void setTaskScheduler(TaskScheduler taskScheduler) {
J
Juergen Hoeller 已提交
152
		Assert.notNull(taskScheduler, "TaskScheduler must not be null");
153 154 155 156 157 158 159 160
		this.taskScheduler = taskScheduler;
		if (this.heartbeatValue == null) {
			this.heartbeatValue = new long[] {10000, 10000};
		}
	}

	/**
	 * Return the configured TaskScheduler.
161
	 * @since 4.2
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
	 */
	public TaskScheduler getTaskScheduler() {
		return this.taskScheduler;
	}

	/**
	 * Configure the value for the heart-beat settings. The first number
	 * represents how often the server will write or send a heartbeat.
	 * The second is how often the client should write. 0 means no heartbeats.
	 * <p>By default this is set to "0, 0" unless the {@link #setTaskScheduler
	 * taskScheduler} in which case the default becomes "10000,10000"
	 * (in milliseconds).
	 * @since 4.2
	 */
	public void setHeartbeatValue(long[] heartbeat) {
		Assert.notNull(heartbeat);
		this.heartbeatValue = heartbeat;
	}

	/**
	 * The configured value for the heart-beat settings.
183
	 * @since 4.2
184 185 186 187 188
	 */
	public long[] getHeartbeatValue() {
		return this.heartbeatValue;
	}

189
	/**
J
Juergen Hoeller 已提交
190 191
	 * Configure a {@link MessageHeaderInitializer} to apply to the headers
	 * of all messages sent to the client outbound channel.
192
	 * <p>By default this property is not set.
193
	 * @since 4.1
194 195 196 197 198 199
	 */
	public void setHeaderInitializer(MessageHeaderInitializer headerInitializer) {
		this.headerInitializer = headerInitializer;
	}

	/**
J
Juergen Hoeller 已提交
200
	 * Return the configured header initializer.
201
	 * @since 4.1
202 203 204 205 206
	 */
	public MessageHeaderInitializer getHeaderInitializer() {
		return this.headerInitializer;
	}

207 208 209 210

	@Override
	public void startInternal() {
		publishBrokerAvailableEvent();
211 212 213 214 215 216 217 218 219
		if (getTaskScheduler() != null) {
			long interval = initHeartbeatTaskDelay();
			if (interval > 0) {
				this.heartbeatFuture = this.taskScheduler.scheduleWithFixedDelay(new HeartbeatTask(), interval);
			}
		}
		else {
			Assert.isTrue(getHeartbeatValue() == null ||
					(getHeartbeatValue()[0] == 0 && getHeartbeatValue()[1] == 0),
J
Juergen Hoeller 已提交
220
					"Heartbeat values configured but no TaskScheduler provided");
221 222 223 224 225 226 227 228 229 230 231 232 233
		}
	}

	private long initHeartbeatTaskDelay() {
		if (getHeartbeatValue() == null) {
			return 0;
		}
		else if (getHeartbeatValue()[0] > 0 && getHeartbeatValue()[1] > 0) {
			return Math.min(getHeartbeatValue()[0], getHeartbeatValue()[1]);
		}
		else {
			return (getHeartbeatValue()[0] > 0 ? getHeartbeatValue()[0] : getHeartbeatValue()[1]);
		}
234 235
	}

236
	@Override
237 238
	public void stopInternal() {
		publishBrokerUnavailableEvent();
239 240 241
		if (this.heartbeatFuture != null) {
			this.heartbeatFuture.cancel(true);
		}
242 243 244 245
	}

	@Override
	protected void handleMessageInternal(Message<?> message) {
246 247 248 249
		MessageHeaders headers = message.getHeaders();
		SimpMessageType messageType = SimpMessageHeaderAccessor.getMessageType(headers);
		String destination = SimpMessageHeaderAccessor.getDestination(headers);
		String sessionId = SimpMessageHeaderAccessor.getSessionId(headers);
250 251 252
		Principal user = SimpMessageHeaderAccessor.getUser(headers);

		updateSessionReadTime(sessionId);
253 254 255 256

		if (!checkDestinationPrefix(destination)) {
			return;
		}
257

258
		if (SimpMessageType.MESSAGE.equals(messageType)) {
259
			logMessage(message);
260 261
			sendMessageToSubscribers(destination, message);
		}
262
		else if (SimpMessageType.CONNECT.equals(messageType)) {
263
			logMessage(message);
264 265 266
			long[] clientHeartbeat = SimpMessageHeaderAccessor.getHeartbeat(headers);
			long[] serverHeartbeat = getHeartbeatValue();
			this.sessions.put(sessionId, new SessionInfo(sessionId, user, clientHeartbeat, serverHeartbeat));
267 268 269
			SimpMessageHeaderAccessor connectAck = SimpMessageHeaderAccessor.create(SimpMessageType.CONNECT_ACK);
			initHeaders(connectAck);
			connectAck.setSessionId(sessionId);
270
			connectAck.setUser(SimpMessageHeaderAccessor.getUser(headers));
271
			connectAck.setHeader(SimpMessageHeaderAccessor.CONNECT_MESSAGE_HEADER, message);
272
			connectAck.setHeader(SimpMessageHeaderAccessor.HEART_BEAT_HEADER, serverHeartbeat);
273
			Message<byte[]> messageOut = MessageBuilder.createMessage(EMPTY_PAYLOAD, connectAck.getMessageHeaders());
274
			getClientOutboundChannel().send(messageOut);
275
		}
276
		else if (SimpMessageType.DISCONNECT.equals(messageType)) {
277
			logMessage(message);
278
			handleDisconnect(sessionId, user, message);
279 280
		}
		else if (SimpMessageType.SUBSCRIBE.equals(messageType)) {
281
			logMessage(message);
282 283 284
			this.subscriptionRegistry.registerSubscription(message);
		}
		else if (SimpMessageType.UNSUBSCRIBE.equals(messageType)) {
285
			logMessage(message);
286 287
			this.subscriptionRegistry.unregisterSubscription(message);
		}
288
	}
289

290 291 292 293 294 295 296 297 298
	private void updateSessionReadTime(String sessionId) {
		if (sessionId != null) {
			SessionInfo info = this.sessions.get(sessionId);
			if (info != null) {
				info.setLastReadTime(System.currentTimeMillis());
			}
		}
	}

299 300 301 302 303 304 305 306
	private void logMessage(Message<?> message) {
		if (logger.isDebugEnabled()) {
			SimpMessageHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, SimpMessageHeaderAccessor.class);
			accessor = (accessor != null ? accessor : SimpMessageHeaderAccessor.wrap(message));
			logger.debug("Processing " + accessor.getShortLogMessage(message.getPayload()));
		}
	}

307 308 309 310 311 312
	private void initHeaders(SimpMessageHeaderAccessor accessor) {
		if (getHeaderInitializer() != null) {
			getHeaderInitializer().initHeaders(accessor);
		}
	}

313
	private void handleDisconnect(String sessionId, Principal user, Message<?> origMessage) {
314 315 316 317 318
		this.sessions.remove(sessionId);
		this.subscriptionRegistry.unregisterAllSubscriptions(sessionId);
		SimpMessageHeaderAccessor accessor = SimpMessageHeaderAccessor.create(SimpMessageType.DISCONNECT_ACK);
		accessor.setSessionId(sessionId);
		accessor.setUser(user);
319 320 321
		if (origMessage != null) {
			accessor.setHeader(SimpMessageHeaderAccessor.DISCONNECT_MESSAGE_HEADER, origMessage);
		}
322 323 324 325 326
		initHeaders(accessor);
		Message<byte[]> message = MessageBuilder.createMessage(EMPTY_PAYLOAD, accessor.getMessageHeaders());
		getClientOutboundChannel().send(message);
	}

327
	protected void sendMessageToSubscribers(String destination, Message<?> message) {
328
		MultiValueMap<String,String> subscriptions = this.subscriptionRegistry.findSubscriptions(message);
J
Juergen Hoeller 已提交
329
		if (!subscriptions.isEmpty() && logger.isDebugEnabled()) {
330
			logger.debug("Broadcasting to " + subscriptions.size() + " sessions.");
331
		}
332
		long now = System.currentTimeMillis();
333 334
		for (String sessionId : subscriptions.keySet()) {
			for (String subscriptionId : subscriptions.get(sessionId)) {
335
				SimpMessageHeaderAccessor headerAccessor = SimpMessageHeaderAccessor.create(SimpMessageType.MESSAGE);
336
				initHeaders(headerAccessor);
337 338 339
				headerAccessor.setSessionId(sessionId);
				headerAccessor.setSubscriptionId(subscriptionId);
				headerAccessor.copyHeadersIfAbsent(message.getHeaders());
340
				Object payload = message.getPayload();
341
				Message<?> reply = MessageBuilder.createMessage(payload, headerAccessor.getMessageHeaders());
342
				try {
343
					getClientOutboundChannel().send(reply);
344 345
				}
				catch (Throwable ex) {
346
					logger.error("Failed to send " + message, ex);
347
				}
348 349 350 351 352 353
				finally {
					SessionInfo info = this.sessions.get(sessionId);
					if (info != null) {
						info.setLastWriteTime(now);
					}
				}
354 355 356
			}
		}
	}
357

358 359
	@Override
	public String toString() {
J
Juergen Hoeller 已提交
360
		return "SimpleBrokerMessageHandler [" + this.subscriptionRegistry + "]";
361 362
	}

363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429

	private static class SessionInfo {

		/* STOMP spec: receiver SHOULD take into account an error margin */
		private static final long HEARTBEAT_MULTIPLIER = 3;

		private final String sessiondId;

		private final Principal user;

		private final long readInterval;

		private final long writeInterval;

		private volatile long lastReadTime;

		private volatile long lastWriteTime;

		public SessionInfo(String sessiondId, Principal user, long[] clientHeartbeat, long[] serverHeartbeat) {
			this.sessiondId = sessiondId;
			this.user = user;
			if (clientHeartbeat != null && serverHeartbeat != null) {
				this.readInterval = (clientHeartbeat[0] > 0 && serverHeartbeat[1] > 0 ?
						Math.max(clientHeartbeat[0], serverHeartbeat[1]) * HEARTBEAT_MULTIPLIER : 0);
				this.writeInterval = (clientHeartbeat[1] > 0 && serverHeartbeat[0] > 0 ?
						Math.max(clientHeartbeat[1], serverHeartbeat[0]) : 0);
			}
			else {
				this.readInterval = 0;
				this.writeInterval = 0;
			}
			this.lastReadTime = this.lastWriteTime = System.currentTimeMillis();
		}

		public String getSessiondId() {
			return this.sessiondId;
		}

		public Principal getUser() {
			return this.user;
		}

		public long getReadInterval() {
			return this.readInterval;
		}

		public long getWriteInterval() {
			return this.writeInterval;
		}

		public long getLastReadTime() {
			return this.lastReadTime;
		}

		public void setLastReadTime(long lastReadTime) {
			this.lastReadTime = lastReadTime;
		}

		public long getLastWriteTime() {
			return this.lastWriteTime;
		}

		public void setLastWriteTime(long lastWriteTime) {
			this.lastWriteTime = lastWriteTime;
		}
	}

J
Juergen Hoeller 已提交
430

431 432 433 434 435 436 437
	private class HeartbeatTask implements Runnable {

		@Override
		public void run() {
			long now = System.currentTimeMillis();
			for (SessionInfo info : sessions.values()) {
				if (info.getReadInterval() > 0 && (now - info.getLastReadTime()) > info.getReadInterval()) {
438
					handleDisconnect(info.getSessiondId(), info.getUser(), null);
439 440 441 442 443 444 445 446 447 448 449 450
				}
				if (info.getWriteInterval() > 0 && (now - info.getLastWriteTime()) > info.getWriteInterval()) {
					SimpMessageHeaderAccessor accessor = SimpMessageHeaderAccessor.create(SimpMessageType.HEARTBEAT);
					accessor.setSessionId(info.getSessiondId());
					accessor.setUser(info.getUser());
					initHeaders(accessor);
					MessageHeaders headers = accessor.getMessageHeaders();
					getClientOutboundChannel().send(MessageBuilder.createMessage(EMPTY_PAYLOAD, headers));
				}
			}
		}
	}
J
Juergen Hoeller 已提交
451

452
}