Spring Boot教學
Spring Boot是什麼?
Spring Boot簡介
Spring Boot主要目標
Spring Boot快速入門
新項目爲什麼需要Spring Boot?
Spring Boot引導過程
Spring Boot核心和限制
Spring Boot Tomcat部署
Spring Boot優點和缺點
Spring Boot構建系統
Spring Boot入門
Spring Boot代碼結構
Spring Boot安裝
Spring Boot Bean和依賴注入
Spring Boot應用程序開發入門
Spring Boot運行器(Runner)
Spring Boot JSP應用實例
Spring Boot應用程序屬性
Spring Boot將WAR文件部署到Tomcat
Spring Boot日誌
Spring Boot Hello World(Thymeleaf)示例
Spring Boot構建RESTful Web服務
Spring Boot非web應用程序實例
Spring Boot異常處理
Spring Boot @ConfigurationProperties實例
Spring Boot攔截器
Spring Boot SLF4J日誌實例
Spring Boot Servlet過濾器
Spring Boot Ajax實例
Spring Boot Tomcat端口號
Spring Boot文件上傳示例(Ajax和REST)
Spring Boot Rest模板
Spring Boot文件上傳示例
Spring Boot文件處理
Spring Boot服務組件
Spring Boot Thymeleaf示例
Spring Boot使用RESTful Web服務
Spring Boot CORS支持
Spring Boot國際化
Spring Boot調度
Spring Boot啓用HTTPS
Spring Boot Eureka服務器
Spring Boost Eureka服務註冊
Spring Boot Zuul代理服務器和路由
Spring Boot雲配置服務器
Spring Boot雲配置客戶端
Spring Boot Actuator
Spring Boot管理服務器
Spring Boot管理客戶端
Spring Boot啓用Swagger2
Spring Boot創建Docker鏡像
Spring Boot跟蹤微服務日誌
Spring Boot Flyway數據庫
Spring Boot發送電子郵件
Spring Boot Hystrix
Spring Boot Web Socket
Spring Boot批量服務
Spring Boot Apache Kafka
Spring Boot單元測試用例
Spring Boot Rest控制器單元測試
Spring Boot數據庫源(連接數據庫)
Spring Boot保護Web應用程序

Spring Boot Web Socket

在本章中,將瞭解和學習如何使用Spring Boot with Web套接字構建交互式Web應用程序。

要使用Web套接字在Spring Boot中構建交互式Web應用程序,需要添加以下依賴項。

Maven用戶應在pom.xml 文件中添加以下依賴項。

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
   <groupId>org.webjars</groupId>
   <artifactId>webjars-locator</artifactId>
</dependency>
<dependency>
   <groupId>org.webjars</groupId>
   <artifactId>sockjs-client</artifactId>
   <version>1.0.2</version>
</dependency>

<dependency>
   <groupId>org.webjars</groupId>
   <artifactId>stomp-websocket</artifactId>
   <version>2.3.3</version>
</dependency>
<dependency>
   <groupId>org.webjars</groupId>
   <artifactId>bootstrap</artifactId>
   <version>3.3.7</version>        </dependency>
<dependency>
   <groupId>org.webjars</groupId>
   <artifactId>jquery</artifactId>
   <version>3.1.0</version>
</dependency>

Gradle用戶可以在build.gradle 文件中添加以下依賴項 -

compile("org.springframework.boot:spring-boot-starter-websocket")
compile("org.webjars:webjars-locator")
compile("org.webjars:sockjs-client:1.0.2")
compile("org.webjars:stomp-websocket:2.3.3")
compile("org.webjars:bootstrap:3.3.7")
compile("org.webjars:jquery:3.1.0")

創建一個消息處理控制器來處理STOMP消息傳遞。STOMP消息可以路由到[@Controller](https://github.com/Controller "@Controller")類文件。 例如,GreetingController被映射爲處理到目標URL => /hello 的消息。

package com.yiibai.websocketapp;

import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Controller;

@Controller
public class GreetingController {
   @MessageMapping("/hello")
   @SendTo("/topic/greetings")
   public Greeting greeting(HelloMessage message) throws Exception {
      Thread.sleep(1000); // simulated delay
      return new Greeting("Hello, " + message.getName() + "!");
   }
}

現在,爲STOMP消息傳遞配置Spring。 編寫一個擴展AbstractWebSocketMessageBrokerConfigurer類的WebSocketConfig類文件,代碼如下所示。

package com.yiibai.websocketapp;

import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;

@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("/yiibai-websocket").withSockJS();
   }
}

[@EnableWebSocketMessageBroker](https://github.com/EnableWebSocketMessageBroker "@EnableWebSocketMessageBroker")註釋用於配置Web套接字消息代理以創建STOMP端點。

可以在src/main/resources/static/index.html下創建一個瀏覽器客戶端文件,如下所示 -

<!DOCTYPE html>
<html>
   <head>
      <title>Hello WebSocket</title>
      <link href = "/webjars/bootstrap/css/bootstrap.min.css" rel = "stylesheet">
      <link href = "/main.css" rel = "stylesheet">
      <script src = "/webjars/jquery/jquery.min.js"></script>
      <script src = "/webjars/sockjs-client/sockjs.min.js"></script>
      <script src = "/webjars/stomp-websocket/stomp.min.js"></script>
      <script src = "/app.js"></script>
   </head>

   <body>
      <noscript>
         <h2 style = "color: #ff0000">
            Seems your browser doesn't support Javascript! Websocket relies on Javascript being
            enabled. Please enable Javascript and reload this page!
         </h2>
      </noscript>
      <div id = "main-content" class = "container">
         <div class = "row">
            <div class = "col-md-6">
               <form class = "form-inline">
                  <div class = "form-group">
                     <label for = "connect">WebSocket connection:</label>
                     <button id = "connect" class = "btn btn-default" type = "submit">Connect</button>
                     <button id = "disconnect" class = "btn btn-default" type = "submit" disabled = "disabled">Disconnect
                     </button>
                  </div>
               </form>
            </div>

            <div class = "col-md-6">
               <form class = "form-inline">
                  <div class = "form-group">
                     <label for = "name">What is your name?</label>
                     <input type = "text" id = "name" class = "form-control" placeholder = "Your name here...">
                  </div>
                  <button id = "send" class = "btn btn-default" type = "submit">Send</button>
               </form>
            </div>
         </div>

         <div class  =  "row">
            <div class  =  "col-md-12">
               <table id  =  "conversation" class = "table table-striped">
                  <thead>
                     <tr>
                        <th>Greetings</th>
                     </tr>
                  </thead>
                  <tbody id  =  "greetings"></tbody>
               </table>
            </div>
         </div>
      </div>
   </body>
</html>

創建一個app.js 文件來使用STOMP來消費和生成消息。

var stompClient = null;

function setConnected(connected) {
   $("#connect").prop("disabled", connected);
   $("#disconnect").prop("disabled", !connected);

   if (connected) {
      $("#conversation").show();
   } else {
      $("#conversation").hide();
   }
   $("#greetings").html("");
}

function connect() {
   var socket = new SockJS('/yiibai-websocket');
   stompClient = Stomp.over(socket);
   stompClient.connect({}, function (frame) {
      setConnected(true);
      console.log('Connected: ' + frame);
      stompClient.subscribe('/topic/greetings', function (greeting) {
         showGreeting(JSON.parse(greeting.body).content);
      });
   });
}
function disconnect() {
   if (stompClient !== null) {
      stompClient.disconnect();
   }
   setConnected(false);
   console.log("Disconnected");
}
function sendName() {
   stompClient.send("/app/hello", {}, JSON.stringify({'name': $("#name").val()}));
}
function showGreeting(message) {
   $("#greetings").append("<tr><td>" + message + "</td></tr>");
}
$(function () {
   $( "form" ).on('submit', function (e) {e.preventDefault();});
   $( "#connect" ).click(function() { connect(); });
   $( "#disconnect" ).click(function() { disconnect(); });
   $( "#send" ).click(function() { sendName(); });
});

主Spring Boot應用程序的代碼如下所示。

package com.yiibai.websocketapp;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class WebsocketappApplication {
   public static void main(String[] args) {
      SpringApplication.run(WebsocketappApplication.class, args);
   }  
}

完整的構建配置文件如下所示。

Maven構建文件 - pom.xml

<?xml version = "1.0" encoding = "UTF-8"?>
<project xmlns = "http://maven.apache.org/POM/4.0.0" 
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0 
   http://maven.apache.org/xsd/maven-4.0.0.xsd">

   <modelVersion>4.0.0</modelVersion>
   <groupId>com.yiibai</groupId>
   <artifactId>websocketapp</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <packaging>jar</packaging>
   <name>websocketapp</name>
   <description>Demo project for Spring Boot</description>

   <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>1.5.9.RELEASE</version>
   </parent>

   <dependencies>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-websocket</artifactId>
      </dependency>
      <dependency>
         <groupId>org.webjars</groupId>
         <artifactId>webjars-locator</artifactId>
      </dependency>
      <dependency>
         <groupId>org.webjars</groupId>
         <artifactId>sockjs-client</artifactId>
         <version>1.0.2</version>
      </dependency>

      <dependency>
         <groupId>org.webjars</groupId>
         <artifactId>stomp-websocket</artifactId>
         <version>2.3.3</version>
      </dependency>
      <dependency>
         <groupId>org.webjars</groupId>
         <artifactId>bootstrap</artifactId>
         <version>3.3.7</version>
      </dependency>

      <dependency>
         <groupId>org.webjars</groupId>
         <artifactId>jquery</artifactId>
         <version>3.1.0</version>
      </dependency>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-test</artifactId>
         <scope>test</scope>
      </dependency>
   </dependencies>

   <properties>
      <java.version>1.8</java.version>
   </properties>

   <build>
      <plugins>
         <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
         </plugin>
      </plugins>
   </build>

</project>

Gradle構建文件 - build.gradle

buildscript {
   repositories {
      mavenCentral()
   }
   dependencies {
      classpath("org.springframework.boot:spring-boot-gradle-plugin:1.5.9.RELEASE")
   }
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'

jar {
   baseName = 'websocketapp'
   version =  '0.1.0'
}
sourceCompatibility = 1.8
targetCompatibility = 1.8

repositories {
   mavenCentral()
}
dependencies {
   compile("org.springframework.boot:spring-boot-starter-websocket")
   compile("org.webjars:webjars-locator")
   compile("org.webjars:sockjs-client:1.0.2")
   compile("org.webjars:stomp-websocket:2.3.3")
   compile("org.webjars:bootstrap:3.3.7")
   compile("org.webjars:jquery:3.1.0")

   testCompile("org.springframework.boot:spring-boot-starter-test")
}

可以創建可執行的JAR文件,並使用以下Maven或Gradle命令運行spring boot應用程序 -

對於Maven,使用如下所示的命令 -

mvn clean install

在「BUILD SUCCESS」之後,可以在target目錄下找到JAR文件。

使用下面給出的命令運行JAR文件 -

java –jar <JARFILE>

在瀏覽器打開URL => http://localhost:8080/ ,得到輸出結果如下圖所示 -

Spring

執行發送和接收消息,如下圖所示:

Spring