在Spring Boot中使用websocket时,我看到了使用以下示例:
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic/");
config.setApplicationDestinationPrefixes("/app");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/greeting");;
}
}
使用@MessageMapping批注指定config.setApplicationDestinationPrefixes(“ / app”)和在控制器中。
我还看到了仅使用enableSimpleBroker()且在控制器中使用@SubscribeMapping的示例。
据我了解,@ MessageMapping负责将收到的消息路由到正确的方法。并且只有在目标包含setApplicationDestinationPrefixes中声明的前缀之一的情况下,才会触发带有此注释的方法。
但是@SubscribeMapping还将消息路由到正确的方法,我们不需要在config类中调用setApplicationDestinationPrefixes()。
有什么区别?
答案 0 :(得分:1)
简短答案
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
</head>
<body>
<p>Hello</p>
<p th:text="${name}"></p>
<p th:text="${todayDate}"></p>
</body>
</html>
your HTML file location is src/main/resources/templates/home.html
By using the below function you can get the final processed HTML as:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<p>Hello</p>
<p>Manoj</p>
<p>30 November 2019</p>
</body>
</html>
@GetMapping("/")
public void process() {
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
templateResolver.setPrefix("templates/");
templateResolver.setCacheable(false);
templateResolver.setSuffix(".html");
templateResolver.setTemplateMode("HTML5");
templateEngine.setTemplateResolver(templateResolver);
Context ctx = new Context();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd MMMM yyyy");
Calendar cal = Calendar.getInstance();
ctx.setVariable("todayDate", dateFormat.format(cal.getTime()));
ctx.setVariable("name", "Manoj");
final String result = templateEngine.process("home", ctx);
System.out.println("result:" + result);
}
注释的方法将仅对目的地为前缀@MessageMapping
且与注释中设置的主题匹配的SEND
消息作出反应。
/app
注释的方法将仅对目标匹配注释中设置的主题的@SubscribeMapping
消息作出反应。
更长的答案
客户端可以发送几种类型的STOMP命令,其中包括SUBSCRIBE
和SUBSCRIBE
。
用SEND
注释的方法将只接收目标为@SubscribeMapping("/topic/topic1")
的{{1}}条消息。即当客户订阅主题SUBSCRIBE
时,将调用此方法。
相反,当客户端将"/topic/topic1"
消息发送到"/topic/topic1"
目的地时,将不会调用此方法。
将为发送到SEND
目标的"/topic/topic1"
消息调用带有@MessageMapping("/topic2")
注释的方法,并且默认情况下,将结果发送到目标SEND
。 / p>
逻辑是,客户端先"/app/topic2"
个,然后"/topic/topic2"
个进入某些主题,并接收服务器(或其他客户端)发送给这些主题的消息。它还可能CONNECT
向某些主题发送一些消息。然后它可能SUBSCRIBE
和SEND
。消息交换的过程由消息代理管理,消息代理可以是简单的内存对象或某些高级产品,例如UNSUBSCRIBE
或DISCONNECT
等。