Spring通过REST API和WebSocket作为中间层,实现JavaScript与RabbitMQ的消息交互:1. Spring集成RabbitMQ并提供POST接口接收前端请求;2. JavaScript调用该接口发送消息,Spring将其转发至队列;3. 消费者处理后通过WebSocket将结果推送给前端,完成双向通信。

JavaScript本身运行在浏览器或Node.js环境中,无法直接与Spring框架的消息队列(如RabbitMQ、Kafka)进行通信。但可以通过中间层实现前后端协同处理消息。常见的做法是:Spring作为后端服务使用消息队列进行异步通信,前端JavaScript通过HTTP或WebSocket与Spring后端交互,间接完成消息的发送与接收。
在Spring Boot项目中集成RabbitMQ,用于接收和发送消息:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
spring:
rabbitmq:
host: localhost
port: 5672
username: guest
password: guest
@Service
public class MessageProducer {
@Autowired
private RabbitTemplate rabbitTemplate;
public void sendMessage(String message) {
rabbitTemplate.convertAndSend("myQueue", message);
}
}
@Service
public class MessageConsumer {
@RabbitListener(queues = "myQueue")
public void receive(String message) {
System.out.println("Received: " + message);
}
}
Spring提供一个REST接口,供前端JavaScript发送消息请求:
@RestController
public class MessageController {
@Autowired
private MessageProducer messageProducer;
@PostMapping("/send")
public ResponseEntity<String> sendMessage(@RequestBody Map<String, String> payload) {
messageProducer.sendMessage(payload.get("msg"));
return ResponseEntity.ok("Message sent!");
}
}
前端JavaScript通过fetch调用Spring的REST接口:
立即学习“Java免费学习笔记(深入)”;
async function sendMsg() {
const res = await fetch('http://localhost:8080/send', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ msg: 'Hello from JS!' })
});
const data = await res.json();
console.log(data);
}
若需从Spring向JavaScript实时推送消息(例如消费队列后的结果),可使用WebSocket:
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws").withSockJS();
}
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.enableSimpleBroker("/topic");
registry.setApplicationDestinationPrefixes("/app");
}
}
@Controller
public class WsController {
@Autowired
private SimpMessagingTemplate messagingTemplate;
public void sendMessageToClient(String message) {
messagingTemplate.convertAndSend("/topic/messages", message);
}
}
<script src="https://cdn.jsdelivr.net/npm/sockjs-client@1/dist/sockjs.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/stompjs@2.3.3/lib/stomp.min.js"></script>
<script>
const socket = new SockJS('/ws');
const stompClient = Stomp.over(socket);
stompClient.connect({}, function(frame) {
stompClient.subscribe('/topic/messages', function(message) {
console.log('Received: ' + message.body);
});
});
</script>
当Spring从RabbitMQ接收到消息后,可在MessageConsumer中调用WsController的sendMessageToClient方法,将消息推送给前端。
基本上就这些。通过HTTP实现JS发送消息到Spring,再由Spring转发至消息队列;通过WebSocket实现Spring将队列消息实时推送到前端JavaScript。这种方式解耦清晰,适用于大多数Web应用。
以上就是JS如何与Spring消息队列集成_JavaScript与Spring消息队列集成的实现方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号