spring-boot(九)websocket配置

分类:spring-boot
阅读:1813
作者:majingjing
发布:2016-12-30 14:41

从servlet3.0开始就已经支持websocket了,现在已经在很多场景广泛的使用. 下面介绍下spring-boot如何配置websocket支持

先看下官网给出的指导意见 QQ截图20161230141746.png

其实官方给的这个文档很简单,关于spring对websocket所做的支持在boot中未作详细说明,但是这并不影响我们来学习.在spring-framework框架中有非常详细的使用说明.想非常透彻的了解spring-websocket请自行学习.

这里仅对整合做出演示. 案例代码在 spring-boot(八)和spring-session集成 集成上进行改造

项目结构图

QQ截图20161230142457.png

在pom中加入依赖

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>

在文件夹 hello/websocket 下建立 MyHandler.javaWebSocketConfig.java

  • MyHandler.java
package hello.websocket;

import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

/**
 * @author majinding888@foxmail.com
 * @date 2016-12-30 下午1:35:45
 */
public class MyHandler extends TextWebSocketHandler {

	@Override
	protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
		session.sendMessage(new TextMessage("服务器的时间: " + System.currentTimeMillis()));
	}

}
  • WebSocketConfig.java
package hello.websocket;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;

/**
 * @author majinding888@foxmail.com
 * @date 2016-12-30 下午1:38:37
 */
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

	@Override
	public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
		registry.addHandler(myHandler(), "/myHandler").withSockJS();
	}

	@Bean
	public WebSocketHandler myHandler() {
		return new MyHandler();
	}

}

注意此处的注解 @Configuration , @EnableWebSocket


其实环境搭建到此已经结束了,为了测试我们还需要页面来发送消息. 页面部分的代码就不做过多结束了,在tomcat7及以上版本都有examples文件夹,里面有websocket的测试页面,直接将echo.html页面复制到目录 /static 下. 启动主启动类,打开浏览器访问 http://localhost:666/echo.html QQ截图20161230143920.png

源代码附件地址: my-springboot-9.zip