springboot整合websocket & 服务器主动推送数据到前端

       一般前端请求服务器接口都是使用主动请求的模式,有ajax等。但分不同使用场景 有不一样的需求, 比如要求实时性比较高的场景使用ajax则不好实现,且实现了开销也大。所以有了websocket这种长链接的形式保持在前端与服务器的通信协议。

现在很多后端框架都使用springboot,那么如何在springboot中整合websocket服务呢?直接上代码,更加清晰明了!

首先 在 pom 中加入 websocket 依赖

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

创建 socketConfig.class 配置类

@Configuration
public class SocketConfig {

    @Bean
    public ServerEndpointExporter serverEndpointExporter() {

        return new ServerEndpointExporter();
    }

}

创建 websocket.class 接口服务类

注意需要声明为@Component ,这样springboot才会注入并管理

@Component
@ServerEndpoint(value = "/webSocket"
评论 13
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值