如何开发基于Netty的HTTP/HTTPS应用程序

2025-05-29 0 93

一、通过 SSL/TLS 保护应用程序

SSL 和 TLS 安全协议层叠在其他协议之上,用以实现数据安全。为了支持 SSL/TLS,Java 提供了 javax.net.ssl 包,它的 SSLContext 和 SSLEngine 类使得实现解密和加密变得相当简单。Netty 通过一个名为 SsLHandler 的 ChannelHandler 实现了这个 API,其中 SSLHandler 在内部使用 SSLEngine 来完成实际工作

Netty 还提供了基于 OpenSSL 工具包的 SSLEngine 实现,比 JDK 提供的 SSLEngine 具有更好的性能。如果 OpenSSL 可用,可以将 Netty 应用程序配置为默认使用 OpenSSLEngine。如果不可用,Netty 将会退回到 JDK 实现

如何开发基于Netty的HTTP/HTTPS应用程序

下述代码展示了如何使用 ChannelInitializer 来将 SslHandler 添加到 ChannelPipeline 中

  1. public class SslChannelInitializer extends ChannelInitializer<Channel> {
  2. private final SslContext context;
  3. private final boolean startTls;
  4. public SslChannelInitializer(SslContext context, boolean startTls) {
  5. this.context = context;
  6. this.startTls = startTls;
  7. }
  8. @Override
  9. protected void initChannel(Channel ch) throws Exception {
  10. SSLEngine engine = context.newEngine(ch.alloc());
  11. ch.pipeline().addFirst("ssl", new SslHandler(engine, startTls));
  12. }
  13. }

大多数情况下,Sslhandler 将是 ChannelPipeline 中的第一个 ChannelHandler,这确保了只有在所有其他的 ChannelHandler 将它们的逻辑应用到数据之后,才会进行加密

SSLHandler 具有一些有用的方法,如表所示,例如,在握手阶段,两个节点将相互验证并且商定一种加密方式,你可以通过配置 SslHandler 来修改它的行为,或者在 SSL/TLS 握手一旦完成之后提供通知,握手阶段之后,所有的数据都将会被加密

方法名称 描述
setHandshakeTimeout(long, TimeUnit)
setHandshakeTimeoutMillis(long)
getHandshakeTimeoutMillis()
设置和获取超时时间,超时之后,握手 ChannelFuture 将会被通知失败
setCloseNotifyTimeout(long, TimeUnit)
setCloseNotifyTimeoutMillis(long)
getCloseNotifyTimeoutMillis()
设置和获取超时时间,超时之后,将会触发一个关闭通知并关闭连接,这也会导致通知该 ChannelFuture 失败
handshakeFuture() 返回一个在握手完成后将会得到通知的 ChannelFuture,如果握手先前已经执行过,则返回一个包含了先前握手结果的 ChannelFuture
close()
close(ChannelPipeline)
close(ChannelHandlerContext, ChannelPromise)
发送 close_notify 以请求关闭并销毁底层的 SslEngine

二、HTTP 编解码器

https://www.kuaiidc.com/tag/http" title="HTTP">HTTP 是基于请求/响应模式的,客户端向服务器发送一个 https://www.kuaiidc.com/tag/http" title="HTTP">HTTP 请求,然后服务器将会返回一个 https://www.kuaiidc.com/tag/http" title="HTTP">HTTP 响应,Netty 提供了多种多种编码器和解码器以简化对这个协议的使用

下图分别展示了生产和消费 https://www.kuaiidc.com/tag/http" title="HTTP">HTTP 请求和 https://www.kuaiidc.com/tag/http" title="HTTP">HTTP 响应的方法

如何开发基于Netty的HTTP/HTTPS应用程序

如何开发基于Netty的HTTP/HTTPS应用程序

如图所示,一个 https://www.kuaiidc.com/tag/http" title="HTTP">HTTP 请求/响应可能由多个数据部分组成,并且总以一个 LastHttpContent 部分作为结束

下表概要地介绍了处理和生成这些消息的 https://www.kuaiidc.com/tag/http" title="HTTP">HTTP 解码器和编码器

名称 描述
HttpRequestEncoder https://www.kuaiidc.com/tag/http" title="HTTP">HTTPRequest、HttpContent 和 LastHttpContent 消息编码为字节
HttpResponseEncoder https://www.kuaiidc.com/tag/http" title="HTTP">HTTPResponse、HttpContent 和 LastHttpContent 消息编码为字节
HttpRequestDecoder 将字节编码为 https://www.kuaiidc.com/tag/http" title="HTTP">HTTPRequest、HttpContent 和 LastHttpContent 消息
HttpResponseDecoder 将字节编码为 https://www.kuaiidc.com/tag/http" title="HTTP">HTTPResponse、HttpContent 和 LastHttpContent 消息

下述代码中的 HttpPipelineInitializer 类展示了将 https://www.kuaiidc.com/tag/http" title="HTTP">HTTP 支持添加到你的应用程序是多么简单 —— 只需要将正确的 ChannelHandler 添加到 ChannelPipeline 中

  1. public class HttpPipelineInitializer extends ChannelInitializer<Channel> {
  2. private final boolean client;
  3. public HttpPipelineInitializer(boolean client) {
  4. this.client = client;
  5. }
  6. @Override
  7. protected void initChannel(Channel ch) throws Exception {
  8. ChannelPipeline pipeline = ch.pipeline();
  9. if (client) {
  10. // 如果是客户端,则添加 HttpResponseDecoder 处理来自服务器的响应
  11. pipeline.addLast("decoder", new HttpResponseDecoder());
  12. // 如果是客户端,则添加 HttpRequestEncoder 向服务器发送请求
  13. pipeline.addLast("encoder", new HttpRequestEncoder());
  14. } else {
  15. // 如果是服务端,则添加 HttpRequestDecoder 处理来自客户端的请求
  16. pipeline.addLast("decoder", new HttpRequestDecoder());
  17. // 如果是客户端,则添加 HttpResponseEncoder 向客户端发送响应
  18. pipeline.addLast("encoder", new HttpResponseEncoder());
  19. }
  20. }
  21. }

三、聚合 https://www.kuaiidc.com/tag/http" title="HTTP">HTTP 消息

在 ChannelInitializer 将 ChannelHandler 安装到 ChannelPipeline 中之后,你就可以处理不同类型的 https://www.kuaiidc.com/tag/http" title="HTTP">HTTPObject 消息了。但由于 https://www.kuaiidc.com/tag/http" title="HTTP">HTTP 请求和响应可能由许多部分组成,因此你需要聚合它们以形成完整的消息。Netty 提供了一个聚合器,它可以将多个消息部分合并为 FullHttpRequest 或者 FullHttpResponse 消息

由于消息分段需要被缓冲,直到可以转发下一个完整的消息给下一个 ChannelInboundHandler,所以这个操作有轻微的开销,其所带来的好处就是你可以不必关心消息碎片了

引入这种自动聚合机制只不过是向 ChannelPipeline 中添加另外一个 ChannelHandler 罢了,下述代码展示了如何做到这一点:

  1. public class HttpAggregatorInitializer extends ChannelInitializer<Channel> {
  2. private final boolean isClient;
  3. public HttpAggregatorInitializer(boolean isClient) {
  4. this.isClient = isClient;
  5. }
  6. @Override
  7. protected void initChannel(Channel ch) throws Exception {
  8. ChannelPipeline pipeline = ch.pipeline();
  9. if (isClient) {
  10. // 如果是客户端,则添加 HttpClientCodec
  11. pipeline.addLast("codec", new HttpClientCodec());
  12. } else {
  13. // 如果是服务器,则添加 HttpServerCodec
  14. pipeline.addLast("codec", new HttpServerCodec());
  15. }
  16. // 将最大的消息大小为 512KB 的 https://www.kuaiidc.com/tag/http" title="HTTP">HTTPObjectAggregator 添加到 ChannelPipeline
  17. pipeline.addLast("aggregator", new HttpObjectAggregator(512 * 1024));
  18. }
  19. }

四、https://www.kuaiidc.com/tag/http" title="HTTP">HTTP 压缩

当使用 https://www.kuaiidc.com/tag/http" title="HTTP">HTTP 时,建议开启压缩功能以尽可能多地减小传输数据的大小。虽然压缩会带来一些消耗,但通常来说它都是一个好主意,尤其是对于文本数据而言

Netty 为压缩和解压都提供了 ChannelHandler 实现,它们同时支持 gzip 和 deflate 编码

客户端可以通过提供以下头部信息来指示服务器它所支持的压缩格式

GET /encrypted-area https://www.kuaiidc.com/tag/http" title="HTTP">HTTP/1.1

Host: www.example.com

Accept-Encoding: gzip, deflate

然而,需要注意的是,服务器没有义务压缩它所发送的数据

  1. public class HttpCompressionInitializer extends ChannelInitializer<Channel> {
  2. private final boolean isClient;
  3. public HttpCompressionInitializer(boolean isClient) {
  4. this.isClient = isClient;
  5. }
  6. @Override
  7. protected void initChannel(Channel ch) throws Exception {
  8. ChannelPipeline pipeline = ch.pipeline();
  9. if (isClient) {
  10. // 如果是客户端,则添加 https://www.kuaiidc.com/tag/http" title="HTTP">HTTPClientCodec
  11. pipeline.addLast("codec", new HttpClientCodec());
  12. // 如果是客户端,则添加 HttpContentDecompressor 以处理来自服务器的压缩内容
  13. pipeline.addLast("decompressor", new HttpContentDecompressor());
  14. } else {
  15. // 如果是服务端,则添加 HttpServerCodec
  16. pipeline.addLast("codec", new HttpServerCodec());
  17. // 如果是服务器,则添加 HttpContentDecompressor 来压缩数据
  18. pipeline.addLast("decompressor", new HttpContentDecompressor());
  19. }
  20. }
  21. }

五、https://www.kuaiidc.com/tag/http" title="HTTP">HTTPS

启用 https://www.kuaiidc.com/tag/http" title="HTTP">HTTPS 只需要将 SslHandler 添加到 ChannelPipeline 的 ChannelHandler 组合中

  1. public class HttpsCodecInitializer extends ChannelInitializer<Channel> {
  2. private final SslContext context;
  3. private final boolean isClient;
  4. public HttpsCodecInitializer(SslContext context, boolean isClient) {
  5. this.context = context;
  6. this.isClient = isClient;
  7. }
  8. @Override
  9. protected void initChannel(Channel ch) throws Exception {
  10. ChannelPipeline pipeline = ch.pipeline();
  11. SSLEngine engine = context.newEngine(ch.alloc());
  12. pipeline.addLast("ssl", new SslHandler(engine));
  13. if (isClient) {
  14. pipeline.addLast("codec", new HttpClientCodec());
  15. } else {
  16. pipeline.addLast("codec", new HttpServerCodec());
  17. }
  18. }
  19. }

六、WebSocket

WebSocket 解决了一个长期存在的问题:既然底层协议(https://www.kuaiidc.com/tag/http" title="HTTP">HTTP)是一个请求/响应模式的交互序列,那么如何实时地发布信息呢?AJAX一定程度上解决了这个问题,但数据流仍然是由客户端所发送的请求驱动的

WebSocket 提供了在单个 TCP 连接上提供双向的通信,它为网页和远程服务器之间的双向通信提供了一种替代 https://www.kuaiidc.com/tag/http" title="HTTP">HTTP 轮询的方案

要想向你的应用程序添加对于 WebSocket 的支持,你需要将适当的客户端或者服务器 WebSocketChannelHandler 添加到 ChannelPipeline 中。这个类将处理由 WebSocket 定义的称为帧的特殊消息类型,如表所示,WebSocketFrame 可以被归类为数据帧或者控制帧

名称 描述
BinaryWebSocketFrame 数据帧:二进制数据
TextWebSocketFrame 数据帧:文本数据
ContinuationWebSocketFrame 数据帧:属于上一个 BinaryWebSocketFrame 或者 TextWebSocketFrame 的文本或者二进制的数据
CloseWebSocketFrame 控制帧:一个 CLOSE 请求,关闭的状态码以及关闭的原因
PingWebSocketFrame 控制帧:请求一个 PongWebSocketFrame
PongWebSocketFrame 控制帧:对 PingWebSocketFrame 请求的响应

因为 Netty 主要是一种服务器端技术,所以我们重点创建 WebSocket 服务器。下述代码展示了使用 WebSocketChannelHandler 的简单示例,这个类会处理协议升级握手,以及三种控制帧 —— Close、Ping 和 Pong,Text 和 Binary 数据帧将会被传递给下一个 ChannelHandler 进行处理

  1. public class WebSocketServerInitializer extends ChannelInitializer<Channel> {
  2. @Override
  3. protected void initChannel(Channel ch) throws Exception {
  4. ch.pipeline().addLast(
  5. new HttpServerCodec(),
  6. new HttpObjectAggregator(65536),
  7. // 如果被请求的端点是 /websocket,则处理该升级握手
  8. new WebSocketServerProtocolHandler("/websocket"),
  9. // TextFrameHandler 处理 TextWebSocketFrame
  10. new TextFrameHandler(),
  11. // BinaryFrameHandler 处理 BinaryWebSocketFrame
  12. new BinaryFrameHandler(),
  13. // ContinuationFrameHandler 处理 Continuation WebSocketFrame
  14. new ContinuationFrameHandler());
  15. }
  16. public static final class TextFrameHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
  17. @Override
  18. protected void messageReceived(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
  19. // do something
  20. }
  21. }
  22. public static final class BinaryFrameHandler extends SimpleChannelInboundHandler<BinaryWebSocketFrame> {
  23. @Override
  24. protected void messageReceived(ChannelHandlerContext ctx, BinaryWebSocketFrame msg) throws Exception {
  25. // do something
  26. }
  27. }
  28. public static final class ContinuationFrameHandler extends SimpleChannelInboundHandler<ContinuationWebSocketFrame> {
  29. @Override
  30. protected void messageReceived(ChannelHandlerContext ctx, ContinuationWebSocketFrame msg) throws Exception {
  31. // do something
  32. }
  33. }
  34. }

以上就是如何开发基于Nettyhttps://www.kuaiidc.com/tag/http" title="HTTP">HTTP/https://www.kuaiidc.com/tag/http" title="HTTP">HTTPS应用程序的详细内容,更多关于Netty https://www.kuaiidc.com/tag/http" title="HTTP">HTTP/https://www.kuaiidc.com/tag/http" title="HTTP">HTTPS的资料请关注快网idc其它相关文章!

原文链接:https://www.cnblogs.com/Yee-Q/p/14941698.html

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 如何开发基于Netty的HTTP/HTTPS应用程序 https://www.kuaiidc.com/104882.html

相关文章

发表评论
暂无评论