Skip to content

发送消息

如果你想从应用程序的任何部分(例如某个定时任务或普通的 HTTP Controller)向已连接的客户端发送消息,该怎么办?

任何组件都可以向 brokerChannel 发送消息。最简单的方法是注入 SimpMessagingTemplate 模板。

使用 SimpMessagingTemplate

通常你会按类型注入它:

java
@Controller
public class GreetingController {

	private final SimpMessagingTemplate template;

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

	@RequestMapping(path="/greetings", method=POST)
	public void greet(String greeting) {
		String text = "[" + getTimestamp() + "]:" + greeting;
		// 发送到目的地 /topic/greetings
		this.template.convertAndSend("/topic/greetings", text);
	}
}
kotlin
@Controller
class GreetingController(private val template: SimpMessagingTemplate) {

	@RequestMapping(path = ["/greetings"], method = [POST])
	fun greet(greeting: String) {
		val text = "[${getTimestamp()}]:$greeting"
		// 发送到目的地 /topic/greetings
		this.template.convertAndSend("/topic/greetings", text)
	}
}

如果有多个相同类型的 Bean,你可以使用其实际名称 brokerMessagingTemplate 进行限定(Qualify)。


补充教学

1. convertAndSend 的灵活性

它不仅可以发送字符串。Spring 会自动使用配置的消息转换器(通常是 Jackson)将 POJO 对象转换为 JSON 字符串。

2. 定时推送场景

在股票行情或系统监控应用中,通常会有一个 Service 类被 @Scheduled 标记。在定时方法里调用 template.convertAndSend 是实现服务器主动推送最标准的方式。

3. 指定用户发送 (@SendToUser 编程式实现)

模板还提供了 convertAndSendToUser(username, destination, payload) 方法。这是实现点对点私信功能的利器,前提是用户已经过身份验证且 Spring 知道其 Principal

Based on Spring Framework.