Grade build dependency

The build.gradle file is configured as follows

buildscript {
	ext {
		springBootVersion = '1.5.9. RELEASE'
	}
	repositories {
		mavenCentral()
	}
	dependencies {
		classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
	}
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'

group = 'com'
version = '0.0.1 - the SNAPSHOT'
sourceCompatibility = 1.8repositories {mavenCentral()} dependencies {compile('org.springframework.boot:spring-boot-starter-data-redis')
	compile('org.springframework.boot:spring-boot-starter-web')
	compile('org.springframework.data:spring-data-redis')
	compile group: 'com.alibaba', name: 'fastjson', version: '1.1.15
	runtime('mysql:mysql-connector-java')

	compile("org.springframework.boot:spring-boot-starter-websocket")
	compile("org.webjars:webjars-locator-core")
	compile("Org. Webjars: sockjs - client: 1.0.2")
	compile("Org. Webjars: stomp - websocket: 2.3.3." ")
	testCompile('org.springframework.boot:spring-boot-starter-test')}Copy the code

Build STOMP messaging services and service interaction processes

Create a resource representation

The service will receive a message containing the name in the STOMP message, the body of which is a JSON object. If the name given is “Test”, the message might look like this:

{
    "username ": "Test"
}
Copy the code

To model a message with a name, you can create a plain old Java object using the username attribute and the corresponding getUsername() method:

public class ReceiveBean {
    private String username;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    @Override
    public String toString() {
        return "UserBeans{" +
                "username='" + username + '\''+'}'; }}Copy the code

After the message is received and the name is extracted, the service processes it by creating a greeting and publishing it on a separate queue to which the client subscribes. The greeting will also be a JSON object that might look something like this:

{
    "content": "Hello, Test!"
}
Copy the code

To model the greeting representation, add another plain old Java object with a Content attribute and the corresponding getContent() method:

public class ServerStatus {
    private String content;

    public ServerStatus() {}
    public ServerStatus (String content) {
        this.content = content;
    }

    public String getContent () {
        returncontent; }}Copy the code

Spring will use the Jackson JSON library to automatically group the type instances Greeting into JSON. Next, create a controller to receive the serverStatus message and send the greeting message. ##### Create a message handling Controller In Spring’s approach to STOMP messaging, STOMP messages can be mapped to the @Controller class. For example, it ServerStatusController is mapped to process messages to the destination “/serverStatus”

@Controller @EnableScheduling public class ServerStatusController { @Autowired private SimpMessagingTemplate simpMessagingTemplate; // When the browser sends a request to the server, the address is mapped by @requestMapping@messagemapping (requestMapping@messagemapping)."/serverStatus")
    @SendTo("/receive/message") // Broadcast all users. // Parameters passed by are automatically injected into userBean. Public ServerStatus ServerStatus (ReceiveBean ReceiveBean) throws InterruptedException {// The return value is broadcast to all subscribers, as specified in the @sendto annotation"/receive/message". Note that the name from the input message has been cleaned up, because in this case it will be echoed back and rerendered in the client's browser DOM.returnnew ServerStatus((int) (Math.random() * 10 + 50)); } @scheduled (fixedRate = 5000) // Extract once every 5 seconds @sendto ("/receive/message") // Broadcast all users public ObjectsendAllMessage() {/ / discovery news simpMessagingTemplate. ConvertAndSend ("/receive/message", new ServerStatus((int) (Math.random() * 10 + 50)));
        return "callback"; }}Copy the code
Configure Spring for STOMP messaging

Configure Spring to enable WebSocket and STOMP messaging.

/** * WebSocketConfig is annotated @Configuration to indicate that it is a Spring Configuration class. * @ EnableWebSocketMessageBroker: @ EnableWebSocketMessageBroker enable WebSocket message processing, supported by message broker. * / @ Configuration / / @ Configuration annotation indicates that it is a Spring Configuration class @ EnableWebSocketMessageBroker / / @ EnableWebSocketMessageBroker Annotations enable WebSocket message processing, supported by the message broker. public class WebsocketConfig implements WebSocketMessageBrokerConfigurer{ @Override public void RegisterStompEndpoints (StompEndpointRegistry Registry) {/* * The registerStompEndpoints() method registers the endpoint "/serverStatus", * Enable the SockJS fallback option so that an alternative transport can be used when WebSocket is not available. * The SockJS client will try to connect to "/serverStatus" and use the best transport available (websocket, Xhr-Streaming, xhr-polling, etc.). *setAllowedOrigins: allows cross-domain */ registry. AddEndpoint ("/serverStatus").setAllowedOrigins("*").withSockJS(); Public void configureMessageBroker(MessageBrokerRegistry registry) { registry.enableSimpleBroker("/receive"); / / callenableSimpleBroker () a simple message broker based on memory, will bring greetings message back to "/ receive" for the prefix client / / registry setApplicationDestinationPrefixes ("/app"); // Specify the "/ app" prefix for messages bound to the @messagemapping annotation method. This prefix will be used to define all message mappings} @override public void configureWebSocketTransport(WebSocketTransportRegistration registry) { } @Override public void configureClientInboundChannel(ChannelRegistration registration) { } @Override public void configureClientOutboundChannel(ChannelRegistration registration) { } @Override public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) { } @Override public void addReturnValueHandlers(List<HandlerMethodReturnValueHandler>returnValueHandlers) {

    }

    @Override
    public boolean configureMessageConverters(List<MessageConverter> messageConverters) {
        return false; }}Copy the code

Browser client

The JavaScript client that sends and receives messages from the server side when the server-side part is ready

SockJS is a browser JavaScript library that provides a Websocket-like object. SockJS gives you a coherent, cross-browser JavaScript API that creates a low-latency, full-duplex, cross-domain communication channel between the browser and the Web server. At the bottom, SockJS first tries to use native Websockets. If that fails, it can use various browser-specific transport protocols and render them in a WebSocket-like abstraction.

Install socket – the client
npm install sockjs-client
Copy the code

Use STOMP over WebSocket to add appropriate message semantics to the communication between the browser and the server. (STOMP — Simple Text Oriented Message Protocol — Message-oriented Simple Text Protocol)

Install STOMPJS
npm install @stomp/stompjs websocket --save
Copy the code
The front-end code is as follows
const SockJS = require('sockjs-client')
const Stomp = require('@stomp/stompjs')
const socket = new SockJS('http://127.0.0.1:8080/serverStatus') const stompClient = stomp.over (socket) // Create Stomp client stompClient.connect({}, (frame) => {// Connect to the serverlet bean = {
      username: 'Test'
   }
   stompClient.send('/serverStatus', {}, json.stringify (bean)) // Send message stompClient.subscribe('/receive/message', (receive) => {// Subscribe and receive messages console.log('greeting', JSON.parse(receive.body))
   })
})
Copy the code

##### effect is shown as follows: