ReverseProxyServer.java 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package com.xiaobao.gateway.protocol.proxy.reverse;
  2. import com.xiaobao.gateway.protocol.config.MediaServer;
  3. import io.netty.bootstrap.ServerBootstrap;
  4. import io.netty.channel.ChannelInitializer;
  5. import io.netty.channel.ChannelOption;
  6. import io.netty.channel.ChannelPipeline;
  7. import io.netty.channel.EventLoopGroup;
  8. import io.netty.channel.nio.NioEventLoopGroup;
  9. import io.netty.channel.socket.SocketChannel;
  10. import io.netty.channel.socket.nio.NioServerSocketChannel;
  11. import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
  12. import io.netty.handler.logging.LogLevel;
  13. import io.netty.handler.logging.LoggingHandler;
  14. import io.netty.util.internal.logging.InternalLogger;
  15. import io.netty.util.internal.logging.InternalLoggerFactory;
  16. import java.util.List;
  17. /**
  18. * 反向代理(代理服务端)
  19. */
  20. public class ReverseProxyServer {
  21. private static final InternalLogger log = InternalLoggerFactory.getInstance(ReverseProxyServer.class);
  22. public static void bootstrap(int port, List<MediaServer> serverList) {
  23. try {
  24. EventLoopGroup bossGroup = new NioEventLoopGroup(1);
  25. EventLoopGroup workerGroup = new NioEventLoopGroup();
  26. try {
  27. ServerBootstrap b = new ServerBootstrap();
  28. b.group(bossGroup, workerGroup)
  29. .channel(NioServerSocketChannel.class)
  30. // .handler(new LoggingHandler(LogLevel.INFO))
  31. .childHandler(new ChannelInitializer<SocketChannel>() {
  32. @Override
  33. public void initChannel(SocketChannel ch) {
  34. ChannelPipeline pipeline = ch.pipeline();
  35. // pipeline.addLast(new LoggingHandler(LogLevel.INFO));
  36. pipeline.addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 2, 0));
  37. pipeline.addLast(new ReverseProxyServerInHandler(serverList));
  38. }
  39. })
  40. .childOption(ChannelOption.AUTO_READ, false)
  41. .bind(port).sync().channel().closeFuture().sync();
  42. } finally {
  43. bossGroup.shutdownGracefully();
  44. workerGroup.shutdownGracefully();
  45. }
  46. } catch (Exception e) {
  47. log.error("启动反向代理出错", e);
  48. }
  49. }
  50. }