之前作服務器推送通常用輪詢,後端主動給客戶端推送不是很好解決。有時候也能夠採用websocketjava
如今看了springwebflux,用它自帶的方法作服務器推送方便多了.react
代碼以下:web
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就能夠了。spring