HelloWebfluxMethodApplication.java 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. /*
  2. * Copyright 2002-2017 the original author or authors.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package sample;
  17. import org.springframework.beans.factory.annotation.Value;
  18. import org.springframework.context.ApplicationContext;
  19. import org.springframework.context.annotation.*;
  20. import org.springframework.http.server.reactive.HttpHandler;
  21. import org.springframework.http.server.reactive.ReactorHttpHandlerAdapter;
  22. import org.springframework.web.reactive.config.EnableWebFlux;
  23. import org.springframework.web.server.adapter.WebHttpHandlerBuilder;
  24. import reactor.ipc.netty.NettyContext;
  25. import reactor.ipc.netty.http.server.HttpServer;
  26. /**
  27. * @author Rob Winch
  28. * @since 5.0
  29. */
  30. @Configuration
  31. @EnableWebFlux
  32. @ComponentScan
  33. public class HelloWebfluxMethodApplication {
  34. @Value("${server.port:8080}")
  35. private int port = 8080;
  36. public static void main(String[] args) throws Exception {
  37. try(AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
  38. HelloWebfluxMethodApplication.class)) {
  39. context.getBean(NettyContext.class).onClose().block();
  40. }
  41. }
  42. @Profile("default")
  43. @Bean
  44. public NettyContext nettyContext(ApplicationContext context) {
  45. HttpHandler handler = WebHttpHandlerBuilder.applicationContext(context)
  46. .build();
  47. ReactorHttpHandlerAdapter adapter = new ReactorHttpHandlerAdapter(handler);
  48. HttpServer httpServer = HttpServer.create("localhost", port);
  49. return httpServer.newHandler(adapter).block();
  50. }
  51. }