如何在 Spring MVC 中配置 Netty。我应该何时何地启动 Netty tcp 服务器? Spring 开始后我应该初始化 netty 吗?有人可以给我看一个例子,比如 Spring 配置 xml 文件或其他东西吗? 谢谢!
最佳答案
这实际上取决于您使用 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();
}
}
这假设 annotation-based configuration在 Spring 中,您可以使用 XML 轻松获得相同的结果,如 Jonathan's 中所述。回答。
当然,你可能更喜欢直接使用 Netty,在这种情况下,同样的原则适用,但你需要深入研究 Netty user guide有点正确引导服务器。
关于java - 结合 Netty 和 Spring MVC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18374277/