SpringBoot实现WebSocket页面消息推送及Redis发布订阅和队列功能

绮梦之旅 2025-01-07T17:01:12+08:00
0 0 272

引言

在现代化的Web应用中,往往需要实现实时消息推送的功能,以提供更好的用户体验。Spring Boot作为一种快速开发框架,提供了简单易用的WebSocket功能,在页面上实现实时消息推送变得非常容易。同时,结合Redis的发布订阅和队列功能,可以更好地支持分布式系统的消息推送。

一、Spring Boot实现WebSocket页面消息推送

Spring Boot提供了spring-boot-starter-websocket依赖,支持WebSocket协议。

1. 导入依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>

2. 编写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");
    }
}

3. 编写WebSocket处理类

@Controller
public class WebSocketController {

    @MessageMapping("/hello")
    @SendTo("/topic/greetings")
    public Greeting greeting(HelloMessage message) throws Exception {
        return new Greeting("Hello, " + message.getName() + "!");
    }
}

4. 编写页面

<!DOCTYPE html>
<html>
<head>
    <title>Spring Boot WebSocket Demo</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="/webjars/sockjs-client/1.3.0/dist/sockjs.min.js"></script>
    <script src="/webjars/stomp-websocket/2.3.3/dist/stomp.min.js"></script>
</head>
<body>
    <script>
        var stompClient = null;

        function connect() {
            var socket = new SockJS('/ws');
            stompClient = Stomp.over(socket);
            stompClient.connect({}, function (frame) {
                console.log('Connected: ' + frame);
                stompClient.subscribe('/topic/greetings', function (greeting) {
                    showGreeting(JSON.parse(greeting.body).content);
                });
            });
        }

        function disconnect() {
            if (stompClient !== null) {
                stompClient.disconnect();
            }
            console.log("Disconnected");
        }

        function sendName() {
            var name = $("#name").val();
            stompClient.send("/app/hello", {}, JSON.stringify({ 'name': name }));
        }

        function showGreeting(message) {
            $("<li>").text(message).appendTo("#greetings");
        }
    </script>

    <div>
        <input type="text" id="name" placeholder="Enter your name"/>
        <button onclick="sendName()">Send</button>
    </div>
    <ul id="greetings"></ul>

    <script>
        connect();
    </script>
</body>
</html>

5. 运行

启动Spring Boot应用后,访问http://localhost:8080,输入名字并点击"Send"按钮,页面上将实时展示接收到的消息。

二、Redis发布订阅和队列功能

Redis作为一种高性能的键值对存储数据库,具备强大的发布订阅和队列功能,可以实现分布式系统的消息推送。

1. 导入依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

2. 配置Redis连接

application.properties中添加以下配置:

spring.redis.host=localhost
spring.redis.port=6379

3. 实现Redis发布订阅功能

发布者

@Service
public class RedisPublisher {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    public void publish(String channel, Object message) {
        redisTemplate.convertAndSend(channel, message);
    }
}

订阅者

@Component
public class RedisSubscriber {
    
    @Autowired
    private RedisMessageListenerContainer listenerContainer;

    @PostConstruct
    public void subscribe() {
        listenerContainer.addMessageListener(new MessageListenerAdapter(new RedisMessageListener()), new ChannelTopic("channel"));
    }

    public class RedisMessageListener implements MessageListener {

        @Override
        public void onMessage(Message message, byte[] bytes) {
            String channel = new String(message.getChannel());
            String content = new String(message.getBody());
            System.out.println("Received message: " + content + " from channel: " + channel);
        }
    }
}

4. 实现Redis队列功能

生产者

@Service
public class RedisProducer {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    public void produce(String queue, Object message) {
        redisTemplate.opsForList().leftPush(queue, message);
    }
}

消费者

@Component
public class RedisConsumer {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Scheduled(fixedDelay = 1000)
    public void consume() {
        Object message = redisTemplate.opsForList().rightPop("queue");
        if (message != null) {
            System.out.println("Consumed message: " + message);
        }
    }
}

5. 运行

通过调用RedisPublisher的publish方法,可以向指定的channel发布消息;通过调用RedisProducer的produce方法,可以向指定的队列发送消息。RedisSubscriber和RedisConsumer会自动接收到相应的消息。

结语

本文介绍了如何使用Spring Boot实现WebSocket页面消息推送功能,并结合Redis的发布订阅和队列功能,使分布式系统更好地支持消息推送。通过学习和使用这些功能,可以提升Web应用的实时通信和消息传递能力,为用户提供更好的体验。

相似文章

    评论 (0)