博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
spring boot websocket + thy模版
阅读量:6328 次
发布时间:2019-06-22

本文共 11100 字,大约阅读时间需要 37 分钟。

hot3.png

一、pom.xml文件配置
4.0.0
com.hxkj
waychat
0.0.1-SNAPSHOT
org.springframework.boot
spring-boot-starter-parent
1.4.0.RELEASE
UTF-8
1.8
org.springframework.boot
spring-boot-starter-web
mysql
mysql-connector-java
org.mybatis.spring.boot
mybatis-spring-boot-starter
1.1.1
org.springframework.boot
spring-boot-configuration-processor
true
org.springframework.boot
spring-boot-starter-websocket
org.springframework.boot
spring-boot-starter-thymeleaf
org.springframework.boot
spring-boot-starter-test
test
org.springframework.boot
spring-boot-devtools
org.springframework.boot
spring-boot-maven-plugin
war
二、application.properties配置#jdbc datasourcespring.datasource.url=jdbc:mysql://127.0.0.1:3306/waychat?useUnicode=true&characterEncoding=utf8spring.datasource.username=rootspring.datasource.password=rootspring.datasource.driver-class-name=com.mysql.jdbc.Driverspring.datasource.tomcat.max-wait=10000spring.datasource.tomcat.max-active=50000spring.datasource.tomcat.test-on-borrow=true# EMBEDDED SERVER CONFIGURATION (ServerProperties)server.port=8080# JACKSON (JacksonProperties)spring.jackson.date-format=yyyy-MM-dd HH:mm:ss# thymeleafspring.thymeleaf.cache=falsespring.thymeleaf.check-template-location=falsespring.thymeleaf.content-type=text/htmlspring.thymeleaf.enabled=truespring.thymeleaf.encoding=UTF-8spring.thymeleaf.mode=HTML5spring.thymeleaf.prefix=classpath:/templates/spring.thymeleaf.suffix=.html# SPRING RESOURCES HANDLING (ResourceProperties)spring.resources.chain.cache=false三、application.java配置启动容器package com.hxkj.waychat;import org.apache.ibatis.session.SqlSessionFactory;import org.apache.log4j.Logger;import org.apache.tomcat.jdbc.pool.DataSource;import org.mybatis.spring.SqlSessionFactoryBean;import org.mybatis.spring.annotation.MapperScan;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.boot.builder.SpringApplicationBuilder;import org.springframework.boot.context.properties.ConfigurationProperties;import org.springframework.boot.web.servlet.ServletComponentScan;import org.springframework.boot.web.support.SpringBootServletInitializer;import org.springframework.context.annotation.Bean;import org.springframework.core.io.support.PathMatchingResourcePatternResolver;import org.springframework.transaction.annotation.EnableTransactionManagement;@EnableTransactionManagement@SpringBootApplication@MapperScan(basePackages={"com.hxkj.waychat.dao"})@ServletComponentScanpublic class Application extends SpringBootServletInitializer { private static Logger logger = Logger.getLogger(Application.class); @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) { return builder.sources(Application.class); } @Bean @ConfigurationProperties(prefix = "spring.datasource") public DataSource dataSource() { return new org.apache.tomcat.jdbc.pool.DataSource(); } @Bean public SqlSessionFactory sqlSessionFactoryBean() throws Exception { SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean(); sqlSessionFactoryBean.setDataSource(dataSource()); PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); sqlSessionFactoryBean.setConfigLocation(resolver.getResource("classpath:/mybatis/config.xml")); sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath:/com/hxkj/waychat/mapper/*Mapper.xml")); sqlSessionFactoryBean.setTypeAliasesPackage("com.hxkj.waychat.entity,com.hxkj.waychat.entity.query,com.hxkj.waychat.entity.result"); return sqlSessionFactoryBean.getObject(); } public static void main(String[] args) { SpringApplication.run(Application.class, args); logger.info("============= SpringBoot Start Success ============="); }}四、WebSocketConfig.java配置package com.hxkj.websocket.config;import org.springframework.context.annotation.Configuration;import org.springframework.messaging.simp.config.MessageBrokerRegistry;import org.springframework.util.AntPathMatcher;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@EnableWebSocketMessageBrokerpublic class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer { @Override public void registerStompEndpoints(StompEndpointRegistry registry) { registry.addEndpoint("/socket").withSockJS() .setInterceptors( new ChatHandlerShareInterceptor()) .setStreamBytesLimit(512 * 1024) .setHttpMessageCacheSize(1000) .setDisconnectDelay(30 * 1000);; } @Override public void configureMessageBroker(MessageBrokerRegistry registry) { registry.enableSimpleBroker("/topic","/user"); registry.setApplicationDestinationPrefixes("/app"); //registry.setPathMatcher(new AntPathMatcher(".")); }}websocket拦截器配置,读取sessionpackage com.hxkj.websocket.config;import java.util.Map;import javax.servlet.http.HttpSession;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.http.server.ServerHttpRequest;import org.springframework.http.server.ServerHttpResponse;import org.springframework.http.server.ServletServerHttpRequest;import org.springframework.web.socket.WebSocketHandler;import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;public class ChatHandlerShareInterceptor extends HttpSessionHandshakeInterceptor { private static Logger logger = LoggerFactory.getLogger(ChatHandlerShareInterceptor.class); @Override public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception ex) { // TODO Auto-generated method stub super.afterHandshake(request, response, wsHandler, ex); } @Override public boolean beforeHandshake(ServerHttpRequest arg0, ServerHttpResponse arg1, WebSocketHandler arg2, Map
arg3) throws Exception { if(arg0 instanceof ServletServerHttpRequest){ ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) arg0; HttpSession session = servletRequest.getServletRequest().getSession(false); if (session != null) { //使用userName区分WebSocketHandler,以便定向发送消息 String httpSessionId = session.getId(); logger.info(httpSessionId); arg3.put("HTTP_SESSION_ID",httpSessionId); }else{ } } return true; }}五、websocket访问连接配置package com.hxkj.websocket.controller;import java.util.Map;import javax.servlet.http.HttpSession;import javax.websocket.Session;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.messaging.handler.annotation.MessageMapping;import org.springframework.messaging.handler.annotation.SendTo;import org.springframework.messaging.simp.SimpMessageHeaderAccessor;import org.springframework.messaging.simp.SimpMessagingTemplate;import org.springframework.messaging.simp.annotation.SendToUser;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;@Controllerpublic class GreetingController { @Autowired private SimpMessagingTemplate simpMessagingTemplate; @RequestMapping("getSession") @ResponseBody public String getSession(HttpSession session){ System.out.println(session.getId()); return "index"; } @RequestMapping("index") public String index(HttpSession session){ System.out.println(session.getId()); return "index"; } @RequestMapping("/helloSocket") public String helloSocket(){ return "hello/index"; } @RequestMapping("/oneToOne") public String oneToOne(){ return "oneToOne"; } @MessageMapping(value="/change-notice") //@SendToUser(value="/topic/notice") //@SendTo(value="/topic/notice") public void greeting(SimpMessageHeaderAccessor headerAccessor,String value){ System.out.println(headerAccessor.getSessionAttributes()); Map
map = headerAccessor.getSessionAttributes(); System.out.println("HTTP_SESSION_ID:"+map.get("HTTP_SESSION_ID")); System.out.println("session:"+headerAccessor.getSessionId()+" value:"+value); this.simpMessagingTemplate.convertAndSend("/topic/notice", value); //return value; } @MessageMapping(value="/change-notice-greetingToOne") //@SendToUser(value="/topic/greetingToOne") public void greetingToOne(SimpMessageHeaderAccessor headerAccessor,String value){ System.out.println(headerAccessor.getSessionAttributes()); Map
map = headerAccessor.getSessionAttributes(); System.out.println("HTTP_SESSION_ID:"+map.get("HTTP_SESSION_ID")); System.out.println("session:"+headerAccessor.getSessionId()+" value:"+value); this.simpMessagingTemplate.convertAndSendToUser(headerAccessor.getSessionId(), "/greetingToOne/", value); //return value; } }六、前台页面设计
Insert title here

this is websocket

聊天区域

one to one配置聊天
Insert title here

this is websocket

聊天区域

 

转载于:https://my.oschina.net/fellowtraveler/blog/731261

你可能感兴趣的文章
spring boot websocket + thy模版
查看>>
查看文件的真实路径
查看>>
如何开发一个自己的 RubyGem?
查看>>
职工系统150206308
查看>>
『中级篇』K8S最小调度单位Pod(62)
查看>>
ACE网络编程思考(一)
查看>>
数据结构的几种存储方式
查看>>
React源码学习——ReactClass
查看>>
JavaScript中几个相似方法对比
查看>>
如何恢复RAWD盘的资料
查看>>
物联网+云平台未来方向之一
查看>>
大作业项目
查看>>
北大校长王恩哥送给毕业学生的十句话
查看>>
IDC简报:2012年全球六大最佳主机服务器提供商
查看>>
HC3i论坛5月份热门资源30个
查看>>
mysqldump导出--数据+结构+(函数+存储过程)
查看>>
浏览器的渲染原理简介
查看>>
获取系统当前时间参数date
查看>>
MySQL性能优化的最佳20+条经验
查看>>
exchange server 相关
查看>>