结合Netty和Spring MVC

如何在Spring MVC中配置Netty。 何时何地应该启动Netty tcp服务器? 一旦Spring开始,我应该初始化netty吗? 有人可以给我看一个例子,比如Spring配置xml文件或eles吗? 谢谢!

这真的取决于你使用Netty的原因。 假设您将其用作在单独端口上运行的嵌入式HTTP服务器,您可以简单地在Spring bean中初始化它。 我过去使用一个名为Nettosphere的有用的Netty / Atmosphere包装器实现了这个目的 :

@Service public class NettyServer implements ServletContextAware { private ServletContext servletContext; private Nettosphere server; @Autowired private MyStatusHandler statusHandler; @PostConstruct public void initialiseNettyServer() { String rootPath = servletContext.getContextPath() + "/api"; server = new Nettosphere.Builder().config( new Config.Builder() .host(SERVER_HOST) .port(SERVER_PORT) .resource(rootPath + "/status", statusHandler) .build()) .build(); server.start(); } @PreDestroy public void shutdownNettyServer() { server.stop(); } } 

这假设在Spring中基于注释的配置 ,您可以使用XML轻松实现相同的结果,如Jonathan的回答中所述。

当然,您可能更喜欢直接使用Netty,在这种情况下适用相同的原则,但您需要深入了解Netty用户指南以正确引导服务器。

只需使用startstop方法创建一个bean,该方法负责启动和关闭Netty服务器,然后使用适当的init和destroy钩子在上下文中注册bean,例如:

  

或者,如果您不想使用XML配置,请使用@PostConstruct@PreDestroy注释。

选项1(只是代码):
这是一个非常好的例子,展示了如何使用支持Servlet的处理程序来引导Netty(后者又将作业委托给Spring MVC) https://github.com/rstoyanchev/netty-spring-mvc

在那里,您定义了ServletNettyHandler和基于Java的Spring MVC配置器( DispatcherServletChannelInitializer ),并且TestController在这些情况下始终使用@Controller@RequestMapping注释。

注意:考虑更新示例的Netty和Spring版本以使其工作。

选项2(只是博客文章):
我找到了一篇描述这个过程的博客文章。 http://www.hypersocket.com/content/?p=12

查看将Netty.io引入Spring框架的Cruzeira项目,实现Servlet API的一个子集https://github.com/fabiofalci/cruzeira

实际上在Spring 5中你可以配置一个Spring 5 Webflux应用程序,它看起来像一个强大的反应式替代品。 以下行( Config.start() )使用Spring上下文与主执行并行运行一个小型HTTP服务器。

 @Configuration public class Config extends DelegatingWebFluxConfiguration{ @Bean String test(){ return "Hello WOrLd"; } @Bean AdminController controller(){ return new AdminController(); } public static void start() { AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(Config.class); HttpHandler handler = WebHttpHandlerBuilder.applicationContext(applicationContext).build(); ReactorHttpHandlerAdapter adapter = new ReactorHttpHandlerAdapter(handler); HttpServer.create("0.0.0.0", 8082).newHandler(adapter).subscribe(); } } 

控制器代码:

 @RestController public class AdminController { @Autowired String text; @GetMapping(path = "/commands") Mono commands(){ return Mono.just(text); } } 

的build.gradle

  compile 'org.springframework:spring-context:5.0.2.RELEASE' compile 'org.springframework:spring-web:5.0.2.RELEASE' compile 'org.springframework:spring-webflux:5.0.2.RELEASE' compile 'io.projectreactor.ipc:reactor-netty:0.7.2.RELEASE' 

PS这个例子只使用没有Spring Boot的Spring,它与侧面嵌入式Web服务器一样好,但你应该考虑使用Spring Boot进行全面的微服务开发。