主要功能如下
代码
public class HttpChannelInitailizer extends ChannelInitializer<Channel> {
private final SslContext context;
private final boolean startTls;
private final boolean isHttpClient; //是滞否为http的客户端
private final boolean compressEnable; //是否带有压缩
public SslChannelInitailizer(SslContext context, boolean startTls, boolean isHttpClient, boolean compress, boolean compressEnable) {
this.context = context;
this.startTls = startTls;
this.isHttpClient = isHttpClient;
this.compressEnable = compressEnable;
}
@Override
protected void initChannel(Channel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
//增加SSL支持
//对于每个SSLHandler实例,都使用了Channel的ByteBufAllocator从SslContext获取一个新的SslEngine
SSLEngine engine = context.newEngine(ch.alloc());
//sslHandler是ChannelPipeline中的第一个ChannelHandler,
//这确保了只有在所有其他的ChannelHandler的逻辑应用到数据之后,才会进行加密
ch.pipeline().addFirst("ssl",new SslHandler(engine,startTls));
if (isHttpClient){
pipeline.addLast("codec",new HttpClientCodec());
}else{
pipeline.addLast("codec",new HttpServerCodec());
}
if (isHttpClient){
pipeline.addLast("decoder",new HttpResponseDecoder());
pipeline.addLast("encooder",new HttpRequestEncoder());
}else{
pipeline.addLast("decoder",new HttpRequestDecoder());
pipeline.addLast("encooder",new HttpResponseEncoder());
}
//自动聚合http的消息片段,有一些开销但不必关心消息片段
//将消息大小定义为512KB的HttpObjectAggregator添加到ChannelPipeline
pipeline.addLast("aggregator",new HttpObjectAggregator(512*1024));
/**
* 服务端启动启动压缩功能,用CPU时钟上的开销来换取减少数据传输量的减小
* 早期版本的jdk(1.6或以前),需要用jzlib来实现压缩,依赖: com.jcraft:jzlib:1.1.3
* GET /encrypted-araa HTTP/1.1
* HOST: www.example.com
* Accept-Encoding: gzip、deflate
*/
if (compressEnable && !isHttpClient){
//需判断客户端是否支持
pipeline.addLast("compressor",new HttpContentCompressor());
}
}
}
网友评论