Spring Boot 2.x实战95 - 事件驱动4 - Websocket之STOMP Websocket

本文介绍了如何在Spring Boot 2.x中使用STOMP Websocket进行全双工通信,包括新建应用、配置STOMP、消息代理支持、消息处理器和安全配置。还提供了客户端页面的订阅与发送消息示例,以及新书《从企业级开发到云原生微服务:Spring Boot 实战》的相关信息,涵盖Spring Boot、响应式编程、事件驱动等内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

4.Websocket

在HTTP协议下,我们可以通过Websocket进行服务端和客户端进行全工通讯,即客户端和服务端都可通过通道直接向彼此发送数据。当我们使用STOMP的时候,应用作为所有连接客户端的消息代理,当然我们使用支持STOMP协议的第三方消息代理如RabbitMQ来负责。

4.1 STOMP Websocket

我们可以在Websockets之上使用STOMP(Simple/Streaming Text Oriented Message Protocol)协议进行交互。

4.1.1 新建应用

新建应用,信息如下:

Group:top.wisely

Artifact:learning-websocket

Dependencies:WebsocketSpring SecurityLombok

build.gradle文件中的依赖如下:

dependencies {
   
	implementation 'org.springframework.boot:spring-boot-starter-websocket'
	implementation 'org.springframework.boot:spring-boot-starter-security'
	compileOnly 'org.projectlombok:lombok'
	annotationProcessor 'org.projectlombok:lombok'
  //...
}
4.1.2 示例
  • 配置STOMP Websocket

    @Configuration
    @EnableWebSocketMessageBroker //1
    public class WebsocketConfig implements WebSocketMessageBrokerConfigurer {
          //2
        @Override
        public void configureMessageBroker(MessageBrokerRegistry registry) {
          //3
            registry.enableSimpleBroker("/topic"); //4
            registry.setApplicationDestinationPrefixes("/app"); //5
        }
    
        @Override
        public void registerStompEndpoints(StompEndpointRegistry registry) {
          
            registry.addEndpoint("/endpoint").withSockJS(); //6
        }
    
    }
    
    1. @EnableWebSocketMessageBroker开启Websocket消息代理的支持,包含给我们配置了消息发送模板SimpMessagingTemplate的Bean;
    2. 通过实现WebSocketMessageBrokerConfigurer接口并重载其方法配置Websocket消息代理;
    3. 通过configureMessageBroker方法配置Websocket消息代理;
    4. 配置消息代理的终点,客户端可订阅监听终点获取信息;
    5. 配置消息处理器(@MessageMapping注解的 方法)的前缀;
    6. WebSocket的端点地址,提供SockJS后备支持;
  • 配置安全

    @Configuration
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
         
    
        @Bean
        PasswordEncoder passwordEncoder(){
         
            return new BCryptPasswordEncoder();
        }
        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
         //1
            auth.inMemoryAuthentication()
                        .withUser("wyf")
                        .password(passwordEncoder().encode("111111"))
                        .roles("USER")
                    .an
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值