zoukankan      html  css  js  c++  java
  • springweb flux 服务器推送事件

    以前做服务器推送一般用轮询,后端主动给客户端推送不是很好解决。有时候也可以采用websocket

    现在看了springwebflux,用它自带的方法做服务器推送方便多了.

    代码如下:

    import org.springframework.http.codec.ServerSentEvent;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    import reactor.core.publisher.Flux;
    import reactor.util.function.Tuples;
    
    import java.time.Duration;
    import java.util.concurrent.ThreadLocalRandom;
    
    /**
     * 服务器推送事件
     * Created by mingge on 2018/5/4.
     */
    @RestController
    @RequestMapping("/sse")
    public class SseController {
        @GetMapping("/randomNumbers")
        public Flux<ServerSentEvent<Integer>> randomNumbers() {
            return Flux.interval(Duration.ofSeconds(1))
                    .map(seq -> Tuples.of(seq, ThreadLocalRandom.current().nextInt()))
                    .map(data -> ServerSentEvent.<Integer>builder()
                            .event("random")
                            .id(Long.toString(data.getT1()))
                            .data(data.getT2())
                            .build());
        }
    }

    就定义普通的controller就可以了。

  • 相关阅读:
    LQB201803乘积尾零
    最大公约数
    快速幂运算
    二分法查找原理
    递归-24点
    递归-爬楼梯
    递归-中项表达式求解
    IDEA的安装基本使用
    SSM和开源框架 ------面试指导
    JDK 8 新特性
  • 原文地址:https://www.cnblogs.com/huzi007/p/9019960.html
Copyright © 2011-2022 走看看