马大波 1 год назад
Родитель
Сommit
4e4ed44e0f

+ 33 - 0
src/main/java/com/xiaobao/gateway/Application.java

@@ -1,11 +1,44 @@
 package com.xiaobao.gateway;
 
+import com.xiaobao.gateway.protocol.config.ForwardConfig;
+import com.xiaobao.gateway.protocol.config.MediaServer;
+import com.xiaobao.gateway.protocol.config.ProxyConfig;
+import com.xiaobao.gateway.protocol.config.ReverseConfig;
+import com.xiaobao.gateway.protocol.proxy.forward.ForwardProxyServer;
+import com.xiaobao.gateway.protocol.proxy.reverse.ReverseProxyServer;
+import io.netty.util.internal.logging.InternalLogger;
+import io.netty.util.internal.logging.InternalLoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.boot.SpringApplication;
 import org.springframework.boot.autoconfigure.SpringBootApplication;
 
+import javax.annotation.PostConstruct;
+import java.util.List;
+
 @SpringBootApplication
 public class Application {
+
+    private static final InternalLogger log = InternalLoggerFactory.getInstance(Application.class);
+
+    @Autowired
+    private ProxyConfig proxyConfig;
+
     public static void main(String[] args) {
         SpringApplication.run(Application.class, args);
     }
+
+    @PostConstruct
+    public void init() {
+        String proxyType = proxyConfig.getType();
+        List<MediaServer> serverList = proxyConfig.getMediaList();
+        if (proxyType.equalsIgnoreCase("client")) {
+            ForwardConfig forward = proxyConfig.getForward();
+            ForwardProxyServer.bootstrap(forward.getReverseHost(), forward.getReversePort(), serverList);
+        } else if (proxyType.equalsIgnoreCase("server")) {
+            ReverseConfig reverse = proxyConfig.getReverse();
+            ReverseProxyServer.bootstrap(reverse.getPort(), serverList);
+        } else {
+            log.warn("代理类型错误", proxyType);
+        }
+    }
 }

+ 15 - 0
src/main/java/com/xiaobao/gateway/protocol/config/ForwardConfig.java

@@ -0,0 +1,15 @@
+package com.xiaobao.gateway.protocol.config;
+
+import lombok.AllArgsConstructor;
+import lombok.Getter;
+import lombok.NoArgsConstructor;
+import lombok.Setter;
+
+@Getter
+@Setter
+@NoArgsConstructor
+@AllArgsConstructor
+public class ForwardConfig {
+    private String reverseHost;
+    private int reversePort;
+}

+ 16 - 0
src/main/java/com/xiaobao/gateway/protocol/config/MediaServer.java

@@ -0,0 +1,16 @@
+package com.xiaobao.gateway.protocol.config;
+
+import lombok.AllArgsConstructor;
+import lombok.Getter;
+import lombok.NoArgsConstructor;
+import lombok.Setter;
+
+@Getter
+@Setter
+@NoArgsConstructor
+@AllArgsConstructor
+public class MediaServer {
+    private String host;
+    private int port;
+    private int proxyPort;
+}

+ 19 - 0
src/main/java/com/xiaobao/gateway/protocol/config/ProxyConfig.java

@@ -0,0 +1,19 @@
+package com.xiaobao.gateway.protocol.config;
+
+import lombok.Getter;
+import lombok.Setter;
+import org.springframework.boot.context.properties.ConfigurationProperties;
+import org.springframework.stereotype.Component;
+
+import java.util.List;
+
+@Getter
+@Setter
+@Component
+@ConfigurationProperties(prefix = "proxy")
+public class ProxyConfig {
+    private String type;
+    private ReverseConfig reverse;
+    private ForwardConfig forward;
+    private List<MediaServer> mediaList;
+}

+ 10 - 0
src/main/java/com/xiaobao/gateway/protocol/config/ReverseConfig.java

@@ -0,0 +1,10 @@
+package com.xiaobao.gateway.protocol.config;
+
+import lombok.Getter;
+import lombok.Setter;
+
+@Getter
+@Setter
+public class ReverseConfig {
+    private int port;
+}

+ 0 - 61
src/main/java/com/xiaobao/gateway/protocol/dto/MediaServerDTO.java

@@ -1,61 +0,0 @@
-package com.xiaobao.gateway.protocol.dto;
-
-import lombok.AllArgsConstructor;
-import lombok.Getter;
-import lombok.NoArgsConstructor;
-import lombok.Setter;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-@Getter
-@Setter
-@NoArgsConstructor
-@AllArgsConstructor
-public class MediaServerDTO {
-    private static final List<MediaServerDTO> MOCK_MEDIA_SERVERS = new ArrayList<>();
-
-    static {
-        MOCK_MEDIA_SERVERS.add(new MediaServerDTO("192.168.66.73", 1935, 8000)); // 媒体服务器
-        MOCK_MEDIA_SERVERS.add(new MediaServerDTO("192.168.66.114", 1935, 8001)); // 媒体服务器
-        MOCK_MEDIA_SERVERS.add(new MediaServerDTO("127.0.0.1", 8007, 8002)); // Echo服务器
-    }
-
-    /**
-     * 服务器地址
-     */
-    private String remoteHost;
-    /**
-     * 服务器端口
-     */
-    private int remotePort;
-    /**
-     * 代理端口(正向代理对外提供端口)
-     * 最大支持2字节端口 2^15 - 1 = 32767
-     */
-    private int proxyPort;
-
-    /**
-     * 获取媒体服务器列表
-     *
-     * @return 服务器列表
-     */
-    public static List<MediaServerDTO> getServerList() {
-        return MOCK_MEDIA_SERVERS;
-    }
-
-    /**
-     * 获取媒体服务器路由表
-     *
-     * @return 路由表
-     */
-    public static Map<Integer, MediaServerDTO> getRouteTable() {
-        Map<Integer, MediaServerDTO> table = new HashMap<>();
-        for (MediaServerDTO server : MOCK_MEDIA_SERVERS) {
-            table.put(server.getProxyPort(), server);
-        }
-        return table;
-    }
-}

+ 3 - 3
src/main/java/com/xiaobao/gateway/protocol/proxy/forward/ForwardProxyClientInHandler.java

@@ -1,6 +1,6 @@
 package com.xiaobao.gateway.protocol.proxy.forward;
 
-import com.xiaobao.gateway.protocol.dto.MediaServerDTO;
+import com.xiaobao.gateway.protocol.config.MediaServer;
 import io.netty.buffer.ByteBuf;
 import io.netty.channel.Channel;
 import io.netty.channel.ChannelFutureListener;
@@ -9,9 +9,9 @@ import io.netty.channel.ChannelInboundHandlerAdapter;
 
 public class ForwardProxyClientInHandler extends ChannelInboundHandlerAdapter {
     private final Channel inboundChannel;
-    private final MediaServerDTO server;
+    private final MediaServer server;
 
-    public ForwardProxyClientInHandler(Channel inboundChannel, MediaServerDTO server) {
+    public ForwardProxyClientInHandler(Channel inboundChannel, MediaServer server) {
         this.inboundChannel = inboundChannel;
         this.server = server;
     }

+ 36 - 42
src/main/java/com/xiaobao/gateway/protocol/proxy/forward/ForwardProxyServer.java

@@ -1,6 +1,6 @@
 package com.xiaobao.gateway.protocol.proxy.forward;
 
-import com.xiaobao.gateway.protocol.dto.MediaServerDTO;
+import com.xiaobao.gateway.protocol.config.MediaServer;
 import io.netty.bootstrap.ServerBootstrap;
 import io.netty.channel.ChannelInitializer;
 import io.netty.channel.ChannelOption;
@@ -26,47 +26,41 @@ public class ForwardProxyServer {
 
     private static final InternalLogger log = InternalLoggerFactory.getInstance(ForwardProxyServer.class);
 
-    /**
-     * 反向代理网关端口
-     */
-    private static final int REMOTE_PORT = 9000;
-    /**
-     * 反向代理网关地址
-     */
-    private static final String REMOTE_HOST = "127.0.0.1";
-
-    public static void main(String[] args) throws InterruptedException {
-        List<MediaServerDTO> serverList = MediaServerDTO.getServerList();
-        ExecutorService executorService = Executors.newFixedThreadPool(serverList.size());
-        for (MediaServerDTO server : serverList) {
-            executorService.submit(() -> {
-                int proxyPort = server.getProxyPort();
-                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<SocketChannel>() {
-                            @Override
-                            public void initChannel(SocketChannel ch) {
-                                ChannelPipeline pipeline = ch.pipeline();
-                                pipeline.addLast(new LoggingHandler(LogLevel.INFO));
-                                pipeline.addLast(new ForwardProxyServerInHandler(REMOTE_HOST, REMOTE_PORT, server));
-                            }
-                        })
-                        .childOption(ChannelOption.AUTO_READ, false)
-                        .bind(proxyPort).sync().channel().closeFuture().sync();
-                } catch (Exception e) {
-                    throw new RuntimeException(e);
-                } finally {
-                    bossGroup.shutdownGracefully();
-                    workerGroup.shutdownGracefully();
-                }
-            });
+    public static void bootstrap(String reverseHost, int reversePort, List<MediaServer> mediaServerList) {
+        try {
+            ExecutorService executorService = Executors.newFixedThreadPool(mediaServerList.size());
+            for (MediaServer server : mediaServerList) {
+                executorService.submit(() -> {
+                    int proxyPort = server.getProxyPort();
+                    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<SocketChannel>() {
+                                @Override
+                                public void initChannel(SocketChannel ch) {
+                                    ChannelPipeline pipeline = ch.pipeline();
+                                    pipeline.addLast(new LoggingHandler(LogLevel.INFO));
+                                    pipeline.addLast(new ForwardProxyServerInHandler(reverseHost, reversePort, server));
+                                }
+                            })
+                            .childOption(ChannelOption.AUTO_READ, false)
+                            .bind(proxyPort).sync().channel().closeFuture().sync();
+                    } catch (Exception e) {
+                        throw new RuntimeException(e);
+                    } finally {
+                        bossGroup.shutdownGracefully();
+                        workerGroup.shutdownGracefully();
+                    }
+                });
+            }
+            executorService.shutdown();
+            executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
+        } catch (Exception e) {
+            log.error("启动正向代理出错", e);
         }
-        executorService.shutdown();
-        executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
     }
 }

+ 6 - 6
src/main/java/com/xiaobao/gateway/protocol/proxy/forward/ForwardProxyServerInHandler.java

@@ -1,6 +1,6 @@
 package com.xiaobao.gateway.protocol.proxy.forward;
 
-import com.xiaobao.gateway.protocol.dto.MediaServerDTO;
+import com.xiaobao.gateway.protocol.config.MediaServer;
 import io.netty.bootstrap.Bootstrap;
 import io.netty.buffer.Unpooled;
 import io.netty.channel.*;
@@ -10,13 +10,13 @@ import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
 public class ForwardProxyServerInHandler extends ChannelInboundHandlerAdapter {
     private final String remoteHost;
     private final int remotePort;
-    private final MediaServerDTO mediaServer;
+    private final MediaServer server;
     private Channel outboundChannel;
 
-    public ForwardProxyServerInHandler(String remoteHost, int remotePort, MediaServerDTO mediaServer) {
+    public ForwardProxyServerInHandler(String remoteHost, int remotePort, MediaServer server) {
         this.remoteHost = remoteHost;
         this.remotePort = remotePort;
-        this.mediaServer = mediaServer;
+        this.server = server;
     }
 
     @Override
@@ -31,8 +31,8 @@ public class ForwardProxyServerInHandler extends ChannelInboundHandlerAdapter {
                 protected void initChannel(SocketChannel ch) throws Exception {
                     ChannelPipeline pipeline = ch.pipeline();
                     pipeline.addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 2, 0));
-                    pipeline.addLast(new ForwardProxyClientOutHandler((short) mediaServer.getProxyPort()));
-                    pipeline.addLast(new ForwardProxyClientInHandler(inboundChannel, mediaServer));
+                    pipeline.addLast(new ForwardProxyClientOutHandler((short) server.getProxyPort()));
+                    pipeline.addLast(new ForwardProxyClientInHandler(inboundChannel, server));
                 }
             })
             .option(ChannelOption.AUTO_READ, false);

+ 5 - 5
src/main/java/com/xiaobao/gateway/protocol/proxy/reverse/ReverseProxyClientInHandler.java

@@ -1,6 +1,6 @@
 package com.xiaobao.gateway.protocol.proxy.reverse;
 
-import com.xiaobao.gateway.protocol.dto.MediaServerDTO;
+import com.xiaobao.gateway.protocol.config.MediaServer;
 import io.netty.buffer.ByteBuf;
 import io.netty.channel.Channel;
 import io.netty.channel.ChannelFutureListener;
@@ -9,11 +9,11 @@ import io.netty.channel.ChannelInboundHandlerAdapter;
 
 public class ReverseProxyClientInHandler extends ChannelInboundHandlerAdapter {
     private final Channel inboundChannel;
-    private final MediaServerDTO mediaServer;
+    private final MediaServer server;
 
-    public ReverseProxyClientInHandler(Channel inboundChannel, MediaServerDTO mediaServer) {
+    public ReverseProxyClientInHandler(Channel inboundChannel, MediaServer server) {
         this.inboundChannel = inboundChannel;
-        this.mediaServer = mediaServer;
+        this.server = server;
     }
 
     @Override
@@ -25,7 +25,7 @@ public class ReverseProxyClientInHandler extends ChannelInboundHandlerAdapter {
     public void channelRead(final ChannelHandlerContext ctx, Object msg) {
         Object packet = msg;
         if (msg instanceof ByteBuf) {
-            int identifier = mediaServer.getProxyPort();
+            int identifier = server.getProxyPort();
             ByteBuf out = ctx.alloc().ioBuffer();
             ByteBuf buf = (ByteBuf) msg;
             int len = buf.readableBytes();

+ 31 - 25
src/main/java/com/xiaobao/gateway/protocol/proxy/reverse/ReverseProxyServer.java

@@ -1,5 +1,6 @@
 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;
@@ -11,39 +12,44 @@ 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 int LOCAL_PORT = 9000;
+    private static final InternalLogger log = InternalLoggerFactory.getInstance(ReverseProxyServer.class);
 
-    public static void main(String[] args) throws Exception {
-        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
-        EventLoopGroup workerGroup = new NioEventLoopGroup();
+    public static void bootstrap(int port, List<MediaServer> serverList) {
         try {
-            ServerBootstrap b = new ServerBootstrap();
-            b.group(bossGroup, workerGroup)
-                .channel(NioServerSocketChannel.class)
-                .handler(new LoggingHandler(LogLevel.INFO))
-                .childHandler(new ChannelInitializer<SocketChannel>() {
-                    @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());
-                    }
-                })
-                .childOption(ChannelOption.AUTO_READ, false)
-                .bind(LOCAL_PORT).sync().channel().closeFuture().sync();
-        } finally {
-            bossGroup.shutdownGracefully();
-            workerGroup.shutdownGracefully();
+            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<SocketChannel>() {
+                        @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);
         }
     }
 }

+ 12 - 4
src/main/java/com/xiaobao/gateway/protocol/proxy/reverse/ReverseProxyServerInHandler.java

@@ -1,18 +1,26 @@
 package com.xiaobao.gateway.protocol.proxy.reverse;
 
-import com.xiaobao.gateway.protocol.dto.MediaServerDTO;
+import com.xiaobao.gateway.protocol.config.MediaServer;
 import io.netty.bootstrap.Bootstrap;
 import io.netty.buffer.ByteBuf;
 import io.netty.channel.*;
 import io.netty.channel.socket.SocketChannel;
 
+import java.util.HashMap;
+import java.util.List;
 import java.util.Map;
 
 public class ReverseProxyServerInHandler extends ChannelInboundHandlerAdapter {
-    private static final Map<Integer, MediaServerDTO> mediaRouteTable = MediaServerDTO.getRouteTable();
+    private final Map<Integer, MediaServer> mediaRouteTable = new HashMap<>();
 
     private Channel outboundChannel;
 
+    public ReverseProxyServerInHandler(List<MediaServer> serverList) {
+        serverList.forEach(server -> {
+            mediaRouteTable.put(server.getProxyPort(), server);
+        });
+    }
+
     @Override
     public void channelActive(ChannelHandlerContext ctx) throws Exception {
         ctx.read();
@@ -28,7 +36,7 @@ public class ReverseProxyServerInHandler extends ChannelInboundHandlerAdapter {
             int identifier = in.readShort();
             if (outboundChannel == null) {
                 if (mediaRouteTable.containsKey(identifier)) {
-                    MediaServerDTO server = mediaRouteTable.get(identifier);
+                    MediaServer server = mediaRouteTable.get(identifier);
                     Channel inboundChannel = ctx.channel();
                     Bootstrap b = new Bootstrap();
                     b.group(inboundChannel.eventLoop())
@@ -41,7 +49,7 @@ public class ReverseProxyServerInHandler extends ChannelInboundHandlerAdapter {
                             }
                         })
                         .option(ChannelOption.AUTO_READ, false);
-                    ChannelFuture f = b.connect(server.getRemoteHost(), server.getRemotePort());
+                    ChannelFuture f = b.connect(server.getHost(), server.getPort());
                     outboundChannel = f.channel();
                     f.addListener((ChannelFutureListener) future -> {
                         if (future.isSuccess()) {

+ 15 - 1
src/main/resources/application.yml

@@ -1,2 +1,16 @@
 server:
-  port: 8000
+  port: 8000
+proxy:
+  type: client
+  reverse:
+    port: 9000
+  forward:
+    reverse-port: 9000
+    reverse-host: 127.0.0.1
+  media-list:
+    - host: 192.168.66.73
+      port: 1935
+      proxy-port: 8000
+    - host: 192.168.66.114
+      port: 1935
+      proxy-port: 8001