当前位置: 首页 > article >正文

【从0到1构建实时聊天系统:Spring Boot + Vue3 + WebSocket全栈实战】


一、项目架构

技术栈清单

  • 后端:Spring Boot 3.0 + WebSocket + STOMP
  • 前端:Vue3 + Pinia + WebSocket Client
  • 部署:Nginx + Docker Compose

二、核心功能实现

1. WebSocket双向通信

// 后端配置类
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/ws")
                .setAllowedOriginPatterns("*")
                .withSockJS();
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        registry.setApplicationDestinationPrefixes("/app");
        registry.enableSimpleBroker("/topic");
    }
}

2. 前端实时消息处理

// Vue3 Composition API实现
const socket = new SockJS('/ws');
const stompClient = Stomp.over(socket);

stompClient.connect({}, () => {
  stompClient.subscribe('/topic/messages', (message) => {
    const chatMessage = JSON.parse(message.body);
    messageStore.addMessage(chatMessage);
  });
});

// 消息发送方法
function sendMessage() {
  stompClient.send("/app/chat", {}, JSON.stringify({
    content: messageContent.value,
    sender: currentUser.value
  }));
}

三、性能优化方案

1. 长连接保活机制

# Nginx配置优化
location /ws/ {
    proxy_pass http://backend;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
    proxy_read_timeout 86400s;
    proxy_send_timeout 86400s;
}

2. 消息压缩方案

压缩算法原始大小压缩后压缩率TPS提升
Gzip2KB0.3KB85%42%
Snappy2KB0.5KB75%35%

四、安全防护体系

1. JWT鉴权方案

// 拦截器实现
@Component
public class WebSocketAuthInterceptor implements HandshakeHandler {
    @Override
    public boolean beforeHandshake(
        ServerHttpRequest request,
        ServerHttpResponse response,
        WebSocketHandler wsHandler,
        Map<String, Object> attributes
    ) {
        String token = request.getHeaders().getFirst("Authorization");
        if (JwtUtil.verifyToken(token)) {
            attributes.put("userId", JwtUtil.getUserId(token));
            return true;
        }
        return false;
    }
}

2. XSS防御策略

// 前端过滤处理
function sanitizeInput(content) {
  return DOMPurify.sanitize(content, {
    ALLOWED_TAGS: ['b', 'i', 'em', 'strong'],
    ALLOWED_ATTR: []
  });
}

五、生产级部署方案

1. Docker Compose配置

version: '3.8'
services:
  app:
    image: your-repo/chat-backend:latest
    ports:
      - "8080:8080"
    environment:
      - SPRING_PROFILES_ACTIVE=prod
    depends_on:
      - redis

  redis:
    image: redis:7.0
    ports:
      - "6379:6379"

http://www.kler.cn/a/577007.html

相关文章:

  • leetcode日记(86)恢复二叉搜索树
  • 无线电家电遥控系统的设计(论文+源码)
  • pyside6学习专栏(十一):在PySide6中实现一简易的画板程序
  • 备赛蓝桥杯之第十五届职业院校组省赛第六题:简易JSX解析器
  • Unity Shader编程】之基础纹理
  • ESP8266 NodeMCU 与 Atmega16 微控制器连接以发送电子邮件
  • 【linux网络编程】套接字socket
  • 迷宫【BFS+结构体\pair】
  • 力扣每日一题——2597. 美丽子集的数目
  • HarmonyOS Next 属性动画和转场动画
  • 【算法 C/C++】一维前缀和
  • 面试过了,总结测试工程师面试题(含答案)
  • Github 2025-03-08Rust开源项目日报Top10
  • 【JAVA架构师成长之路】【Redis】第15集:Redis大Key问题分析与解决方案
  • FPGA学习篇——Verilog学习5(reg,wire区分及模块例化)
  • 大数据表高效导入导出解决方案,mysql数据库LOAD DATA命令和INTO OUTFILE命令详解
  • AORO P9000 PRO三防平板携手RTK高精度定位,电力巡检效率倍增
  • ShardingSphere 和 Spring 的动态数据源切换机制的对比以及原理
  • 解决电脑问题(5)——鼠标问题
  • 后门攻击仓库 backdoor attack