SimpleBrokerMessageHandler.java 8.4 KB
Newer Older
1
/*
2
 * Copyright 2002-2014 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.util.Collection;
20

21 22
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
23
import org.springframework.messaging.MessageHeaders;
24
import org.springframework.messaging.SubscribableChannel;
25 26
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.SimpMessageType;
27
import org.springframework.messaging.support.MessageBuilder;
28
import org.springframework.messaging.support.MessageHeaderAccessor;
29
import org.springframework.messaging.support.MessageHeaderInitializer;
30
import org.springframework.util.Assert;
31
import org.springframework.util.MultiValueMap;
32
import org.springframework.util.PathMatcher;
33 34

/**
35 36 37 38
 * 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.
 *
39 40 41
 * @author Rossen Stoyanchev
 * @since 4.0
 */
42
public class SimpleBrokerMessageHandler extends AbstractBrokerMessageHandler {
43

44 45
	private static final byte[] EMPTY_PAYLOAD = new byte[0];

46
	private SubscriptionRegistry subscriptionRegistry;
47

48 49
	private PathMatcher pathMatcher;

50 51
	private MessageHeaderInitializer headerInitializer;

52 53

	/**
54 55
	 * Create a SimpleBrokerMessageHandler instance with the given message channels
	 * and destination prefixes.
56 57
	 * @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)
58
	 * @param brokerChannel the channel for the application to send messages to the broker
59
	 * @param destinationPrefixes prefixes to use to filter out messages
60
	 */
61
	public SimpleBrokerMessageHandler(SubscribableChannel clientInboundChannel, MessageChannel clientOutboundChannel,
62 63
			SubscribableChannel brokerChannel, Collection<String> destinationPrefixes) {

64 65
		super(clientInboundChannel, clientOutboundChannel, brokerChannel, destinationPrefixes);
		this.subscriptionRegistry = new DefaultSubscriptionRegistry();
66 67 68
	}


69 70 71 72 73 74 75 76
	/**
	 * 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.
	 */
77
	public void setSubscriptionRegistry(SubscriptionRegistry subscriptionRegistry) {
P
Phillip Webb 已提交
78
		Assert.notNull(subscriptionRegistry, "SubscriptionRegistry must not be null");
79
		this.subscriptionRegistry = subscriptionRegistry;
80 81 82 83 84 85 86 87 88
		initPathMatcherToUse();
	}

	private void initPathMatcherToUse() {
		if (this.pathMatcher != null) {
			if (this.subscriptionRegistry instanceof DefaultSubscriptionRegistry) {
				((DefaultSubscriptionRegistry) this.subscriptionRegistry).setPathMatcher(this.pathMatcher);
			}
		}
89 90
	}

91 92
	public SubscriptionRegistry getSubscriptionRegistry() {
		return this.subscriptionRegistry;
93 94
	}

95 96 97 98 99 100 101 102 103
	/**
	 * When configured, the given PathMatcher is passed down to the
	 * SubscriptionRegistry to use for matching destination to subscriptions.
	 */
	public void setPathMatcher(PathMatcher pathMatcher) {
		this.pathMatcher = pathMatcher;
		initPathMatcherToUse();
	}

104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
	/**
	 * Configure a {@link MessageHeaderInitializer} to apply to the headers of all
	 * messages sent to the client outbound channel.
	 *
	 * <p>By default this property is not set.
	 */
	public void setHeaderInitializer(MessageHeaderInitializer headerInitializer) {
		this.headerInitializer = headerInitializer;
	}

	/**
	 * @return the configured header initializer.
	 */
	public MessageHeaderInitializer getHeaderInitializer() {
		return this.headerInitializer;
	}

121 122 123 124

	@Override
	public void startInternal() {
		publishBrokerAvailableEvent();
125 126
	}

127
	@Override
128 129 130 131 132 133
	public void stopInternal() {
		publishBrokerUnavailableEvent();
	}

	@Override
	protected void handleMessageInternal(Message<?> message) {
134

135 136 137 138
		MessageHeaders headers = message.getHeaders();
		SimpMessageType messageType = SimpMessageHeaderAccessor.getMessageType(headers);
		String destination = SimpMessageHeaderAccessor.getDestination(headers);
		String sessionId = SimpMessageHeaderAccessor.getSessionId(headers);
139 140 141 142

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

144 145 146 147 148 149
		SimpMessageHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, SimpMessageHeaderAccessor.class);
		if (accessor == null) {
			throw new IllegalStateException(
					"No header accessor (not using the SimpMessagingTemplate?): " + message);
		}

150
		if (SimpMessageType.MESSAGE.equals(messageType)) {
151
			logMessage(message);
152 153
			sendMessageToSubscribers(destination, message);
		}
154
		else if (SimpMessageType.CONNECT.equals(messageType)) {
155
			logMessage(message);
156 157 158
			SimpMessageHeaderAccessor connectAck = SimpMessageHeaderAccessor.create(SimpMessageType.CONNECT_ACK);
			initHeaders(connectAck);
			connectAck.setSessionId(sessionId);
159
			connectAck.setUser(SimpMessageHeaderAccessor.getUser(headers));
160 161
			connectAck.setHeader(SimpMessageHeaderAccessor.CONNECT_MESSAGE_HEADER, message);
			Message<byte[]> messageOut = MessageBuilder.createMessage(EMPTY_PAYLOAD, connectAck.getMessageHeaders());
162
			getClientOutboundChannel().send(messageOut);
163
		}
164
		else if (SimpMessageType.DISCONNECT.equals(messageType)) {
165
			logMessage(message);
166
			this.subscriptionRegistry.unregisterAllSubscriptions(sessionId);
167 168 169
			SimpMessageHeaderAccessor disconnectAck = SimpMessageHeaderAccessor.create(SimpMessageType.DISCONNECT_ACK);
			initHeaders(disconnectAck);
			disconnectAck.setSessionId(sessionId);
170
			disconnectAck.setUser(SimpMessageHeaderAccessor.getUser(headers));
171 172
			Message<byte[]> messageOut = MessageBuilder.createMessage(EMPTY_PAYLOAD, disconnectAck.getMessageHeaders());
			getClientOutboundChannel().send(messageOut);
173 174
		}
		else if (SimpMessageType.SUBSCRIBE.equals(messageType)) {
175
			logMessage(message);
176 177 178
			this.subscriptionRegistry.registerSubscription(message);
		}
		else if (SimpMessageType.UNSUBSCRIBE.equals(messageType)) {
179
			logMessage(message);
180 181
			this.subscriptionRegistry.unregisterSubscription(message);
		}
182
	}
183

184 185 186 187 188 189 190 191
	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()));
		}
	}

192 193 194 195 196 197
	private void initHeaders(SimpMessageHeaderAccessor accessor) {
		if (getHeaderInitializer() != null) {
			getHeaderInitializer().initHeaders(accessor);
		}
	}

198
	protected void sendMessageToSubscribers(String destination, Message<?> message) {
199
		MultiValueMap<String,String> subscriptions = this.subscriptionRegistry.findSubscriptions(message);
200 201
		if ((subscriptions.size() > 0) && logger.isDebugEnabled()) {
			logger.debug("Broadcasting to " + subscriptions.size() + " sessions.");
202
		}
203 204
		for (String sessionId : subscriptions.keySet()) {
			for (String subscriptionId : subscriptions.get(sessionId)) {
205
				SimpMessageHeaderAccessor headerAccessor = SimpMessageHeaderAccessor.create(SimpMessageType.MESSAGE);
206
				initHeaders(headerAccessor);
207 208 209
				headerAccessor.setSessionId(sessionId);
				headerAccessor.setSubscriptionId(subscriptionId);
				headerAccessor.copyHeadersIfAbsent(message.getHeaders());
210
				Object payload = message.getPayload();
211
				Message<?> reply = MessageBuilder.createMessage(payload, headerAccessor.getMessageHeaders());
212
				try {
213
					getClientOutboundChannel().send(reply);
214 215
				}
				catch (Throwable ex) {
216
					logger.error("Failed to send " + message, ex);
217 218 219 220
				}
			}
		}
	}
221

222 223 224 225 226
	@Override
	public String toString() {
		return "SimpleBroker[" + this.subscriptionRegistry + "]";
	}

227
}