WebFlux开发基础篇--请求构造

本人正在构建的一个开源的项目地址:教育之星

修改POM文件,引入webflux的依赖


            org.springframework.boot
            spring-boot-starter-webflux
        

一:注解方式,这种方式其实和传统的WebMvc的方式基本一致

@RestController
@Api(tags = "测试管理")
public class TestController {


    @GetMapping("/test")
    public ComResponse test(ServerHttpRequest serverRequest){
        return ComResponse.successResponse("1111");
    }
}

直接访问即可,这里需要注意的是,HTTPServletRequest在这里是不能用的,换成了ServerHttpRequest。

二:函数式变成的方式:

config配置:

import com.clark.daxian.gateway.handler.TestHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerResponse;

import static org.springframework.web.reactive.function.server.RequestPredicates.*;

@Configuration
public class RoutingConfiguration {

    @Bean
    public RouterFunction monoRouterFunction(TestHandler userHandler) {
        return RouterFunctions.route(GET("/api/test").and(accept(MediaType.APPLICATION_JSON)), userHandler::test);
    }
}

handler配置:

import com.clark.daxian.api.response.ComResponse;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.ServerRequest;
import reactor.core.publisher.Mono;
import org.springframework.web.reactive.function.server.ServerResponse;



@Component
public class TestHandler {

    public Mono test(ServerRequest request){
        Mono test = Mono.just(ComResponse.successResponse());
        Mono notFound = ServerResponse.notFound().build();

        return test
                .flatMap(customer -> ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).body(BodyInserters.fromObject(test)))
                .switchIfEmpty(notFound);
    }
}

启动访问即可

你可能感兴趣的:(webflux)