webflux-上手

webflux-上手

起男 1,407 2021-12-21

webflux-上手

  1. 导入依赖

    <dependency>
    	<groupId>org.springframework.boot</groupId>
    	<artifactId>spring-boot-starter-webflux</artifactId>
    </dependency>
    
  2. 业务代码

    @Component
    public class TestHandler {
    
        public Mono<ServerResponse> test(ServerRequest request){
            return ServerResponse.ok()
                    .header("Content-Type","text/html;charset=UTF-8")
                    .body(BodyInserters.fromValue("test info..."));
        }
    }
    
  3. 配置路由

    @Configuration
    public class TestRouter {
        @Bean
        public RouterFunction<ServerResponse> test(TestHandler testHandler){
            //此时绑定的访问模式为get请求模式,而后设置了具体的访问地址“test”
            return RouterFunctions.route(RequestPredicates.GET("test")//匹配最终处理路由地址
                            .and(RequestPredicates.accept(MediaType.TEXT_PLAIN)),//匹配的请求类型
                    testHandler::test);
        }
    }
    

整合spring boot

可以通过springmvc的注解形式,代替原本的路由

@RestController
@RequestMapping("test")
public class TestController {

    @GetMapping("mono")
    public Mono<String> getMono(){
        return Mono.create(stringMonoSink -> stringMonoSink.success("mono info..."));
    }

    @GetMapping("flux")
    public Flux<String> getFlux(){
        List<String> list = new ArrayList<>();
        for (int i=0; i<10; i++){
            list.add("flux:"+i);
        }
        return Flux.fromIterable(list);
    }
}

websocket

  1. 实现websocket支持

    @Component
    @Slf4j
    public class EchoHandler implements WebSocketHandler {
        @Override
        public Mono<Void> handle(WebSocketSession session) {
            log.info("websocket客户端握手信息:{}",session.getHandshakeInfo().getUri());
            return session.send(session.receive()
                    .map(mag->session.textMessage("echo"+mag.getPayloadAsText())));
        }
    }
    
  2. websocket配置

    @Configuration
    public class WebSocketConfig {
        @Bean
        public HandlerMapping handlerMapping(EchoHandler echoHandler){
            Map<String, WebSocketHandler> map = new HashMap<>();
            map.put("/ws/{token}",echoHandler);//配置映射模型
            SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();//映射处理
            mapping.setOrder(Ordered.HIGHEST_PRECEDENCE); //设置最高优先级
            mapping.setUrlMap(map);//映射路径
            return mapping;
        }
    
        @Bean
        public WebSocketHandlerAdapter webSocketHandlerAdapter(){
            return new WebSocketHandlerAdapter();//处理配置器
        }
    }