Sending Messages

如果你希望从应用程序的任何部分向连接的客户端发送消息,该怎么做?任何应用程序组件都可以将消息发送到 brokerChannel。最简单的方法是注入一个 SimpMessagingTemplate 并使用它来发送消息。通常情况下,你会按类型注入它,如下面的示例所示:

What if you want to send messages to connected clients from any part of the application? Any application component can send messages to the brokerChannel. The easiest way to do so is to inject a SimpMessagingTemplate and use it to send messages. Typically, you would inject it by type, as the following example shows:

@Controller
public class GreetingController {

	private SimpMessagingTemplate template;

	@Autowired
	public GreetingController(SimpMessagingTemplate template) {
		this.template = template;
	}

	@RequestMapping(path="/greetings", method=POST)
	public void greet(String greeting) {
		String text = "[" + getTimestamp() + "]:" + greeting;
		this.template.convertAndSend("/topic/greetings", text);
	}

}

但是,你也可以通过它的名称(brokerMessagingTemplate)限定它,如果存在其他同类型的 bean 的话。

However, you can also qualify it by its name (brokerMessagingTemplate), if another bean of the same type exists.