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

带JMS的Spring Boot应用嵌入式Tomcat并发运行及端口排障

问题描述

开发集成JMS的Spring Boot应用,计划通过嵌入式Tomcat本地运行,实现流程:Postman -> RestController -> Service -> 投递消息至队列。但启动应用时出现错误:

Description:

Web server failed to start. Port 8082 was already in use.

误以为问题是Tomcat与JMS资源竞争导致,寻求配置嵌入式Tomcat与JMS并发运行的方法或其他可行方案。

解决方案

首先明确:该错误与Tomcat和JMS的资源竞争无关,仅为8082端口被其他进程占用,先解决端口问题,再确保JMS配置正确即可。

1. 解决端口占用问题

  • 更换Spring Boot Tomcat端口
    在application.properties中修改端口为未被占用的数值:
    server.port=8083
    
    若使用application.yml,配置如下:
    server:
      port: 8083
    
  • 杀掉占用8082端口的进程
    • Windows系统:打开命令提示符,依次执行:
      netstat -ano | findstr :8082
      taskkill /F /PID <上述命令返回的进程PID>
      
    • Linux/macOS系统:打开终端,依次执行:
      lsof -i :8082
      kill -9 <上述命令返回的进程PID>
      

2. JMS与嵌入式Tomcat并发运行的配置

Spring Boot中嵌入式Tomcat与JMS天然兼容,只需正确配置JMS客户端即可,以下以常用的ActiveMQ为例:

  • 引入依赖(pom.xml):
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-activemq</artifactId>
    </dependency>
    
  • 配置JMS连接信息(application.properties):
    # ActiveMQ默认端口为61616,与Tomcat端口无冲突
    spring.activemq.broker-url=tcp://localhost:61616
    spring.activemq.user=admin
    spring.activemq.password=admin
    
  • Service层消息投递示例:
    @Service
    public class JmsMessageService {
        private final JmsTemplate jmsTemplate;
    
        // 构造注入替代@Autowired(更符合Spring规范)
        public JmsMessageService(JmsTemplate jmsTemplate) {
            this.jmsTemplate = jmsTemplate;
        }
    
        public void sendToQueue(String queueName, String content) {
            jmsTemplate.convertAndSend(queueName, content);
        }
    }
    
  • RestController层触发示例:
    @RestController
    @RequestMapping("/api/messages")
    public class MessageController {
        private final JmsMessageService messageService;
    
        public MessageController(JmsMessageService messageService) {
            this.messageService = messageService;
        }
    
        @PostMapping("/send")
        public ResponseEntity<String> sendMessage(@RequestParam String queueName, @RequestParam String content) {
            messageService.sendToQueue(queueName, content);
            return ResponseEntity.ok("消息已成功投递至队列");
        }
    }
    

3. 其他可行方案

  • 切换嵌入式Web服务器:若不想使用Tomcat,可替换为Undertow或Jetty,只需修改依赖(移除spring-boot-starter-web中的Tomcat依赖,引入对应服务器依赖),端口配置逻辑不变。
  • 独立JMS服务:若无需Rest接口触发,可将JMS消息投递逻辑做成无Web层的Spring Boot应用,但此方案不符合当前Postman调用的需求,仅作备选。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 19:02:32