Spring websocket over STOMP usage guide

Enable STOMP

The Spring framework provides websocket-based STOMP support, which requires the use spring-messagingof and spring-websocketmodules. 
In the following configuration, a stomp terminal with the prefix is ​​registered , and the /portfolioclient can use this url to establish a websocket connection. 
If the destination /appof the message starts with , it will be forwarded to the message processing method of the response (such as the method annotated with @MessageMapping), if it starts with /topic, /queueit will be forwarded to the message broker (broker), which will be broadcast by the broker to connected clients end.

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/portfolio").withSockJS();
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.setApplicationDestinationPrefixes("/app");//这个前缀不需要与web项目名相同,可以自己随意指定
        config.enableSimpleBroker("/topic", "/queue");//这里配置了两个前缀,若是destination以这两个前缀开头,则会转发给该Broker
    }

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

or use XML

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:websocket="http://www.springframework.org/schema/websocket"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/websocket
        http://www.springframework.org/schema/websocket/spring-websocket.xsd">

    <websocket:message-broker application-destination-prefix="/app">
        <websocket:stomp-endpoint path="/portfolio">
            <websocket:sockjs/>
        </websocket:stomp-endpoint>
        <websocket:simple-broker prefix="/topic, /queue"/>
    </websocket:message-broker>

</beans>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

Here, js is used as the client of stomp. You need to use stomp.js and sockjs-client, which /spring-websocket-portfoliois the project name of the web app and the name /portfolioof the stomp terminal.

var socket = new SockJS("/spring-websocket-portfolio/portfolio");
var stompClient = Stomp.over(socket);
stompClient.connect({}, function(frame) {
}
  • 1
  • 2
  • 3
  • 4
  • 1
  • 2
  • 3
  • 4

If sockjs is not applicable, you can use the native websocket api

var socket = new WebSocket("/spring-websocket-portfolio/portfolio");
var stompClient = Stomp.over(socket);
stompClient.connect({}, function(frame) {
}
  • 1
  • 2
  • 3
  • 4
  • 1
  • 2
  • 3
  • 4

News flow

这里写图片描述
The flow of Message in the application is such a process, as shown above. If the destination starts with /app, it will be handed over to the annotation method through the request channel for processing. After processing, it will be forwarded to SimpleBroker according to the default path (if you do not use the default path, you can use @SendTo to specify the path). After processing, it will be handed over to the response. channel returns connected clients. 
If the destination starts with /topic, it will be directly handed over to SimpleBroker for processing.

@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/portfolio");
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        registry.setApplicationDestinationPrefixes("/app");
        registry.enableSimpleBroker("/topic");
    }

}

@Controller
public class GreetingController {

    @MessageMapping("/greeting") 
    @SendTo("/topic/greetings")
    public String handle(String greeting) {
        return "[" + getTimestamp() + ": " + greeting;
    }
    @SubscribeMapping("/init")
    public String init(){
         return "init";
    }

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31

使用@SubscribeMapping注解,处理client的subscribe请求,被注解的方法将直接返回一个信息给连接的client,不会经过Broker.常用于进行初始化操作。若是在该方法上使用了@SendTo,则会转发至broker处理。

使用Template发送数据

上面我们介绍了如何在controller中发送数据给clients,spring还提供了一个叫做SimpMessagingTemplate的模板,以便我们在应用的任何地方发送数据给Broker

@Controller
public class GreetingController {
    @Autowired
    private SimpMessagingTemplate template;

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

}

@Service
public class GreetingServiceImpl {
    @Autowired
    private SimpMessagingTemplate template;

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

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

常用的注解

destination映射是支持Ant风格的,如"/foo*""/foo/**"。也支持路径参数"/foo/{id}",可以在方法参数中使用@DestinationVariable注解来引用它 
@MessageMapping 注解的方法可以使用下列参数: 
* 使用@Payload方法参数用于获取消息中的payload(即消息的内容) 
* 使用@Header 方法参数用于获取特定的头部 
* 使用@Headers方法参数用于获取所有的头部存放到一个map中 
Java.security.Principal 方法参数用于获取在websocket握手阶段使用的用户信息

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325860220&siteId=291194637