当前位置:   article > 正文

Springboot集成WebSocket实现即时通讯_springboot+websocket+netty+redis实现聊天功能

springboot+websocket+netty+redis实现聊天功能

  1. 在SpringBoot的pom.xml文件里添加依赖:

  1. <!-- websocket -->
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-websocket</artifactId>
  5. </dependency>

  1. 在配置中加入 WebSocketConfig.java

  1. import org.springframework.context.annotation.Bean;
  2. import org.springframework.context.annotation.Configuration;
  3. import org.springframework.web.socket.server.standard.ServerEndpointExporter;
  4. @Configuration
  5. public class WebSocketConfig {
  6. /**
  7. * 注入一个ServerEndpointExporter,该Bean会自动注册使用@ServerEndpoint注解申明的websocket endpoint
  8. */
  9. @Bean
  10. public ServerEndpointExporter serverEndpointExporter() {
  11. return new ServerEndpointExporter();
  12. }
  13. }

  1. 新建component文件夹,加入WebSocketServer.java

  1. import cn.hutool.json.JSONArray;
  2. import cn.hutool.json.JSONObject;
  3. import cn.hutool.json.JSONUtil;
  4. import org.slf4j.Logger;
  5. import org.slf4j.LoggerFactory;
  6. import org.springframework.stereotype.Component;
  7. import javax.websocket.*;
  8. import javax.websocket.server.PathParam;
  9. import javax.websocket.server.ServerEndpoint;
  10. import java.util.Map;
  11. import java.util.concurrent.ConcurrentHashMap;
  12. /**
  13. * @author websocket服务
  14. */
  15. @ServerEndpoint(value = "/imserver/{username}")
  16. @Component
  17. public class WebSocketServer {
  18. private static final Logger log = LoggerFactory.getLogger(WebSocketServer.class);
  19. /**
  20. * 记录当前在线连接数
  21. */
  22. public static final Map<String, Session> sessionMap = new ConcurrentHashMap<>();
  23. /**
  24. * 连接建立成功调用的方法
  25. */
  26. @OnOpen
  27. public void onOpen(Session session, @PathParam("username") String username) {
  28. sessionMap.put(username, session);
  29. log.info("有新用户加入,username={}, 当前在线人数为:{}", username, sessionMap.size());
  30. JSONObject result = new JSONObject();
  31. JSONArray array = new JSONArray();
  32. result.set("users", array);
  33. for (Object key : sessionMap.keySet()) {
  34. JSONObject jsonObject = new JSONObject();
  35. jsonObject.set("username", key);
  36. // {"username", "zhang", "username": "admin"}
  37. array.add(jsonObject);
  38. }
  39. // {"users": [{"username": "zhang"},{ "username": "admin"}]}
  40. sendAllMessage(JSONUtil.toJsonStr
声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号