package com.xiaobao.gateway.protocol.proxy.reverse; import com.xiaobao.gateway.protocol.config.MediaServer; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.ChannelPipeline; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.codec.LengthFieldBasedFrameDecoder; import io.netty.handler.logging.LogLevel; import io.netty.handler.logging.LoggingHandler; import io.netty.util.internal.logging.InternalLogger; import io.netty.util.internal.logging.InternalLoggerFactory; import java.util.List; /** * 反向代理(代理服务端) */ public class ReverseProxyServer { private static final InternalLogger log = InternalLoggerFactory.getInstance(ReverseProxyServer.class); public static void bootstrap(int port, List serverList) { try { EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) // .handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new ChannelInitializer() { @Override public void initChannel(SocketChannel ch) { ChannelPipeline pipeline = ch.pipeline(); // pipeline.addLast(new LoggingHandler(LogLevel.INFO)); pipeline.addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 2, 0)); pipeline.addLast(new ReverseProxyServerInHandler(serverList)); } }) .childOption(ChannelOption.AUTO_READ, false) .bind(port).sync().channel().closeFuture().sync(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } } catch (Exception e) { log.error("启动反向代理出错", e); } } }