一、pom.xml文件配置二、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 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 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
聊天区域