You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在本地主机运行多实例Angular+Spring Boot仿Gmail应用?

本地运行双Angular实例+Spring Boot后端实现仿Gmail互发邮件演示

一、启动两个Angular前端实例

直接通过指定不同端口启动即可,无需修改代码:

  • 第一个实例(默认端口):执行 ng serve,访问地址 http://localhost:4200
  • 第二个实例:执行 ng serve --port 4201,访问地址 http://localhost:4201

二、Spring Boot后端跨域配置

后端不需要特意区分前端端口,只需允许这两个本地端口的跨域请求,确保前端能正常调用接口:

全局跨域配置

创建配置类添加全局CORS规则:

@Configuration
public class CorsConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("http://localhost:4200", "http://localhost:4201")
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .allowedHeaders("*")
                .allowCredentials(true);
    }
}

这样两个前端实例都能正常和后端交互,后端处理请求时只需按业务逻辑执行(比如保存邮件到数据库、查询收件箱),不用关心请求来自哪个端口。

三、实现前端实例间的邮件同步

当A实例给B实例发邮件后,B实例不会自动感知新邮件,需通过以下两种方式实现同步:

方案1:定时轮询(快速上手)

在Angular的收件箱组件中,定时调用后端查询接口获取最新邮件:

import { interval } from 'rxjs';
import { switchMap } from 'rxjs/operators';
import { EmailService } from './email.service';

// 组件内代码
export class InboxComponent implements OnInit {
  inboxMails: Mail[] = [];

  constructor(private emailService: EmailService) {}

  ngOnInit(): void {
    // 每5秒刷新一次收件箱
    interval(5000)
      .pipe(switchMap(() => this.emailService.getInbox()))
      .subscribe(mails => {
        this.inboxMails = mails;
      });
  }
}

方案2:WebSocket实时推送(更高效)

集成WebSocket让后端在有新邮件时主动推送给收件人前端:

  1. 后端WebSocket配置
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableSimpleBroker("/topic"); // 消息代理前缀
        config.setApplicationDestinationPrefixes("/app"); // 应用请求前缀
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/ws")
                .setAllowedOrigins("http://localhost:4200", "http://localhost:4201")
                .withSockJS(); // 兼容低版本浏览器
    }
}
  1. 后端发送推送逻辑
    当邮件保存成功后,向收件人专属的topic发送消息:
@Autowired
private SimpMessagingTemplate messagingTemplate;

// 保存邮件后调用
public void sendMailNotification(String recipientId, Mail newMail) {
    messagingTemplate.convertAndSend("/topic/mail/" + recipientId, newMail);
}
  1. Angular前端订阅WebSocket
    使用STOMP客户端连接后端,订阅对应topic接收新邮件并刷新列表:
import { Stomp } from '@stomp/stompjs';
import SockJS from 'sockjs-client';

// 组件内初始化WebSocket连接
connectWebSocket(userId: string) {
  const socket = new SockJS('http://localhost:8080/ws');
  const stompClient = Stomp.over(socket);

  stompClient.connect({}, () => {
    stompClient.subscribe(`/topic/mail/${userId}`, (message) => {
      const newMail = JSON.parse(message.body);
      // 将新邮件添加到收件箱列表头部
      this.inboxMails.unshift(newMail);
    });
  });
}

四、测试流程

  1. 启动Spring Boot后端(默认端口8080)
  2. 启动第一个Angular实例(4200端口),登录用户A
  3. 启动第二个Angular实例(4201端口),登录用户B
  4. 在A实例中撰写邮件并发送给B,后端将邮件存入数据库
  5. B实例通过轮询或WebSocket实时获取新邮件,完成演示

内容的提问来源于stack exchange,提问作者Marwan Esam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 09:00:41