代理网关设计与实现(基于NETTY)
簡介:本文重點在代理網關本身的設計與實現,而非代理資源的管理與維護。
作者 | 新然
來源 | 阿里技術公眾號
一 問題背景
從提取的代理中,選取指定地域,添加認證信息,請求獲取結果;
本文設計實現一個通過的代理網關:
本文重點在代理網關本身的設計與實現,而非代理資源的管理與維護。
注:本文包含大量可執行的JAVA代碼以解釋代理相關的原理
二 技術路線
本文的技術路線。在實現代理網關之前,首先介紹下代理相關的原理及如何實現
最后,本文要構建代理網關,本質上就是一個非透明的上游代理,并給出詳細的設計與實現。
1 透明代理
透明代理是代理網關的基礎,本文采用JAVA原生的NIO進行詳細介紹。在實現代理網關時,實際使用的為NETTY框架。原生NIO的實現對理解NETTY的實現有幫助。
透明代理設計三個交互方,客戶端、代理服務、服務端,其原理是:
需要注意的點是:
完整的透明代理的實現不到約300行代碼,完整摘錄如下:
@Slf4j public class SimpleTransProxy {public static void main(String[] args) throws IOException {int port = 8006;ServerSocketChannel localServer = ServerSocketChannel.open();localServer.bind(new InetSocketAddress(port));Reactor reactor = new Reactor();// REACTOR線程GlobalThreadPool.REACTOR_EXECUTOR.submit(reactor::run);// WORKER單線程調試while (localServer.isOpen()) {// 此處阻塞等待連接SocketChannel remoteClient = localServer.accept();// 工作線程GlobalThreadPool.WORK_EXECUTOR.submit(new Runnable() {@SneakyThrows@Overridepublic void run() {// 代理到遠程SocketChannel remoteServer = new ProxyHandler().proxy(remoteClient);// 透明傳輸reactor.pipe(remoteClient, remoteServer).pipe(remoteServer, remoteClient);}});}} }@Data class ProxyHandler {private String method;private String host;private int port;private SocketChannel remoteServer;private SocketChannel remoteClient;/*** 原始信息*/private List<ByteBuffer> buffers = new ArrayList<>();private StringBuilder stringBuilder = new StringBuilder();/*** 連接到遠程* @param remoteClient* @return* @throws IOException*/public SocketChannel proxy(SocketChannel remoteClient) throws IOException {this.remoteClient = remoteClient;connect();return this.remoteServer;}public void connect() throws IOException {// 解析METHOD, HOST和PORTbeforeConnected();// 鏈接REMOTE SERVERcreateRemoteServer();// CONNECT請求回應,其他請求WRITE THROUGHafterConnected();}protected void beforeConnected() throws IOException {// 讀取HEADERreadAllHeader();// 解析HOST和PORTparseRemoteHostAndPort();}/*** 創建遠程連接* @throws IOException*/protected void createRemoteServer() throws IOException {remoteServer = SocketChannel.open(new InetSocketAddress(host, port));}/*** 連接建立后預處理* @throws IOException*/protected void afterConnected() throws IOException {// 當CONNECT請求時,默認寫入200到CLIENTif ("CONNECT".equalsIgnoreCase(method)) {// CONNECT默認為443端口,根據HOST再解析remoteClient.write(ByteBuffer.wrap("HTTP/1.0 200 Connection Established\r\nProxy-agent: nginx\r\n\r\n".getBytes()));} else {writeThrouth();}}protected void writeThrouth() {buffers.forEach(byteBuffer -> {try {remoteServer.write(byteBuffer);} catch (IOException e) {e.printStackTrace();}});}/*** 讀取請求內容* @throws IOException*/protected void readAllHeader() throws IOException {while (true) {ByteBuffer clientBuffer = newByteBuffer();int read = remoteClient.read(clientBuffer);clientBuffer.flip();appendClientBuffer(clientBuffer);if (read < clientBuffer.capacity()) {break;}}}/*** 解析出HOST和PROT* @throws IOException*/protected void parseRemoteHostAndPort() throws IOException {// 讀取第一批,獲取到METHODmethod = parseRequestMethod(stringBuilder.toString());// 默認為80端口,根據HOST再解析port = 80;if ("CONNECT".equalsIgnoreCase(method)) {port = 443;}this.host = parseHost(stringBuilder.toString());URI remoteServerURI = URI.create(host);host = remoteServerURI.getHost();if (remoteServerURI.getPort() > 0) {port = remoteServerURI.getPort();}}protected void appendClientBuffer(ByteBuffer clientBuffer) {buffers.add(clientBuffer);stringBuilder.append(new String(clientBuffer.array(), clientBuffer.position(), clientBuffer.limit()));}protected static ByteBuffer newByteBuffer() {// buffer必須大于7,保證能讀到methodreturn ByteBuffer.allocate(128);}private static String parseRequestMethod(String rawContent) {// create urireturn rawContent.split("\r\n")[0].split(" ")[0];}private static String parseHost(String rawContent) {String[] headers = rawContent.split("\r\n");String host = "host:";for (String header : headers) {if (header.length() > host.length()) {String key = header.substring(0, host.length());String value = header.substring(host.length()).trim();if (host.equalsIgnoreCase(key)) {if (!value.startsWith("http://") && !value.startsWith("https://")) {value = "http://" + value;}return value;}}}return "";}}@Slf4j @Data class Reactor {private Selector selector;private volatile boolean finish = false;@SneakyThrowspublic Reactor() {selector = Selector.open();}@SneakyThrowspublic Reactor pipe(SocketChannel from, SocketChannel to) {from.configureBlocking(false);from.register(selector, SelectionKey.OP_READ, new SocketPipe(this, from, to));return this;}@SneakyThrowspublic void run() {try {while (!finish) {if (selector.selectNow() > 0) {Iterator<SelectionKey> it = selector.selectedKeys().iterator();while (it.hasNext()) {SelectionKey selectionKey = it.next();if (selectionKey.isValid() && selectionKey.isReadable()) {((SocketPipe) selectionKey.attachment()).pipe();}it.remove();}}}} finally {close();}}@SneakyThrowspublic synchronized void close() {if (finish) {return;}finish = true;if (!selector.isOpen()) {return;}for (SelectionKey key : selector.keys()) {closeChannel(key.channel());key.cancel();}if (selector != null) {selector.close();}}public void cancel(SelectableChannel channel) {SelectionKey key = channel.keyFor(selector);if (Objects.isNull(key)) {return;}key.cancel();}@SneakyThrowspublic void closeChannel(Channel channel) {SocketChannel socketChannel = (SocketChannel)channel;if (socketChannel.isConnected() && socketChannel.isOpen()) {socketChannel.shutdownOutput();socketChannel.shutdownInput();}socketChannel.close();} }@Data @AllArgsConstructor class SocketPipe {private Reactor reactor;private SocketChannel from;private SocketChannel to;@SneakyThrowspublic void pipe() {// 取消監聽clearInterestOps();GlobalThreadPool.PIPE_EXECUTOR.submit(new Runnable() {@SneakyThrows@Overridepublic void run() {int totalBytesRead = 0;ByteBuffer byteBuffer = ByteBuffer.allocate(1024);while (valid(from) && valid(to)) {byteBuffer.clear();int bytesRead = from.read(byteBuffer);totalBytesRead = totalBytesRead + bytesRead;byteBuffer.flip();to.write(byteBuffer);if (bytesRead < byteBuffer.capacity()) {break;}}if (totalBytesRead < 0) {reactor.closeChannel(from);reactor.cancel(from);} else {// 重置監聽resetInterestOps();}}});}protected void clearInterestOps() {from.keyFor(reactor.getSelector()).interestOps(0);to.keyFor(reactor.getSelector()).interestOps(0);}protected void resetInterestOps() {from.keyFor(reactor.getSelector()).interestOps(SelectionKey.OP_READ);to.keyFor(reactor.getSelector()).interestOps(SelectionKey.OP_READ);}private boolean valid(SocketChannel channel) {return channel.isConnected() && channel.isRegistered() && channel.isOpen();} }以上,借鑒NETTY:
測試
代理的測試比較簡單,指向代碼后,代理服務監聽8006端口,此時:
curl -x 'localhost:8006'?http://httpbin.org/get測試HTTP請求
curl -x 'localhost:8006'?https://httpbin.org/get測試HTTPS請求
注意,此時代理服務代理了HTTPS請求,但是并不需要-k選項,指示非安全的代理。因為代理服務本身并沒有作為一個中間人,并沒有解析出客戶端和遠程服務端通信的內容。在非透明代理時,需要解決這個問題。
2 非透明代理
非透明代理,需要解析出客戶端和遠程服務端傳輸的內容,并做相應的處理。
當傳輸為HTTP協議時,SocketPipe傳輸的數據即為明文的數據,可以攔截后直接做處理。
當傳輸為HTTPS協議時,SocketPipe傳輸的有效數據為加密數據,并不能透明處理。
另外,無論是傳輸的HTTP協議還是HTTPS協議,SocketPipe讀到的都為非完整的數據,需要做聚批的處理。
SslSocketChannel封裝原理
考慮到目前JDK自帶的NIO的SocketChannel并不支持SSL;已有的SSLSocket是阻塞的OIO。如圖:
可以看出
以下,代碼實現 SslSocketChannel
public class SslSocketChannel {/*** 握手加解密需要的四個存儲*/protected ByteBuffer myAppData; // 明文protected ByteBuffer myNetData; // 密文protected ByteBuffer peerAppData; // 明文protected ByteBuffer peerNetData; // 密文/*** 握手加解密過程中用到的異步執行器*/protected ExecutorService executor = Executors.newSingleThreadExecutor();/*** 原NIO 的 CHANNEL*/protected SocketChannel socketChannel;/*** SSL 引擎*/protected SSLEngine engine;public SslSocketChannel(SSLContext context, SocketChannel socketChannel, boolean clientMode) throws Exception {// 原始的NIO SOCKETthis.socketChannel = socketChannel;// 初始化BUFFERSSLSession dummySession = context.createSSLEngine().getSession();myAppData = ByteBuffer.allocate(dummySession.getApplicationBufferSize());myNetData = ByteBuffer.allocate(dummySession.getPacketBufferSize());peerAppData = ByteBuffer.allocate(dummySession.getApplicationBufferSize());peerNetData = ByteBuffer.allocate(dummySession.getPacketBufferSize());dummySession.invalidate();engine = context.createSSLEngine();engine.setUseClientMode(clientMode);engine.beginHandshake();}/*** 參考 https://docs.oracle.com/javase/8/docs/technotes/guides/security/jsse/JSSERefGuide.html* 實現的 SSL 的握手協議* @return* @throws IOException*/protected boolean doHandshake() throws IOException {SSLEngineResult result;HandshakeStatus handshakeStatus;int appBufferSize = engine.getSession().getApplicationBufferSize();ByteBuffer myAppData = ByteBuffer.allocate(appBufferSize);ByteBuffer peerAppData = ByteBuffer.allocate(appBufferSize);myNetData.clear();peerNetData.clear();handshakeStatus = engine.getHandshakeStatus();while (handshakeStatus != HandshakeStatus.FINISHED && handshakeStatus != HandshakeStatus.NOT_HANDSHAKING) {switch (handshakeStatus) {case NEED_UNWRAP:if (socketChannel.read(peerNetData) < 0) {if (engine.isInboundDone() && engine.isOutboundDone()) {return false;}try {engine.closeInbound();} catch (SSLException e) {log.debug("收到END OF STREAM,關閉連接.", e);}engine.closeOutbound();handshakeStatus = engine.getHandshakeStatus();break;}peerNetData.flip();try {result = engine.unwrap(peerNetData, peerAppData);peerNetData.compact();handshakeStatus = result.getHandshakeStatus();} catch (SSLException sslException) {engine.closeOutbound();handshakeStatus = engine.getHandshakeStatus();break;}switch (result.getStatus()) {case OK:break;case BUFFER_OVERFLOW:peerAppData = enlargeApplicationBuffer(engine, peerAppData);break;case BUFFER_UNDERFLOW:peerNetData = handleBufferUnderflow(engine, peerNetData);break;case CLOSED:if (engine.isOutboundDone()) {return false;} else {engine.closeOutbound();handshakeStatus = engine.getHandshakeStatus();break;}default:throw new IllegalStateException("無效的握手狀態: " + result.getStatus());}break;case NEED_WRAP:myNetData.clear();try {result = engine.wrap(myAppData, myNetData);handshakeStatus = result.getHandshakeStatus();} catch (SSLException sslException) {engine.closeOutbound();handshakeStatus = engine.getHandshakeStatus();break;}switch (result.getStatus()) {case OK :myNetData.flip();while (myNetData.hasRemaining()) {socketChannel.write(myNetData);}break;case BUFFER_OVERFLOW:myNetData = enlargePacketBuffer(engine, myNetData);break;case BUFFER_UNDERFLOW:throw new SSLException("加密后消息內容為空,報錯");case CLOSED:try {myNetData.flip();while (myNetData.hasRemaining()) {socketChannel.write(myNetData);}peerNetData.clear();} catch (Exception e) {handshakeStatus = engine.getHandshakeStatus();}break;default:throw new IllegalStateException("無效的握手狀態: " + result.getStatus());}break;case NEED_TASK:Runnable task;while ((task = engine.getDelegatedTask()) != null) {executor.execute(task);}handshakeStatus = engine.getHandshakeStatus();break;case FINISHED:break;case NOT_HANDSHAKING:break;default:throw new IllegalStateException("無效的握手狀態: " + handshakeStatus);}}return true;}/*** 參考 https://docs.oracle.com/javase/8/docs/technotes/guides/security/jsse/JSSERefGuide.html* 實現的 SSL 的傳輸讀取協議* @param consumer* @throws IOException*/public void read(Consumer<ByteBuffer> consumer) throws IOException {// BUFFER初始化peerNetData.clear();int bytesRead = socketChannel.read(peerNetData);if (bytesRead > 0) {peerNetData.flip();while (peerNetData.hasRemaining()) {peerAppData.clear();SSLEngineResult result = engine.unwrap(peerNetData, peerAppData);switch (result.getStatus()) {case OK:log.debug("收到遠程的返回結果消息為:" + new String(peerAppData.array(), 0, peerAppData.position()));consumer.accept(peerAppData);peerAppData.flip();break;case BUFFER_OVERFLOW:peerAppData = enlargeApplicationBuffer(engine, peerAppData);break;case BUFFER_UNDERFLOW:peerNetData = handleBufferUnderflow(engine, peerNetData);break;case CLOSED:log.debug("收到遠程連接關閉消息.");closeConnection();return;default:throw new IllegalStateException("無效的握手狀態: " + result.getStatus());}}} else if (bytesRead < 0) {log.debug("收到END OF STREAM,關閉連接.");handleEndOfStream();}}public void write(String message) throws IOException {write(ByteBuffer.wrap(message.getBytes()));}/*** 參考 https://docs.oracle.com/javase/8/docs/technotes/guides/security/jsse/JSSERefGuide.html* 實現的 SSL 的傳輸寫入協議* @param message* @throws IOException*/public void write(ByteBuffer message) throws IOException {myAppData.clear();myAppData.put(message);myAppData.flip();while (myAppData.hasRemaining()) {myNetData.clear();SSLEngineResult result = engine.wrap(myAppData, myNetData);switch (result.getStatus()) {case OK:myNetData.flip();while (myNetData.hasRemaining()) {socketChannel.write(myNetData);}log.debug("寫入遠程的消息為: {}", message);break;case BUFFER_OVERFLOW:myNetData = enlargePacketBuffer(engine, myNetData);break;case BUFFER_UNDERFLOW:throw new SSLException("加密后消息內容為空.");case CLOSED:closeConnection();return;default:throw new IllegalStateException("無效的握手狀態: " + result.getStatus());}}}/*** 關閉連接* @throws IOException*/public void closeConnection() throws IOException {engine.closeOutbound();doHandshake();socketChannel.close();executor.shutdown();}/*** END OF STREAM(-1)默認是關閉連接* @throws IOException*/protected void handleEndOfStream() throws IOException {try {engine.closeInbound();} catch (Exception e) {log.error("END OF STREAM 關閉失敗.", e);}closeConnection();}}以上:
SslSocketChannel測試服務端
基于以上封裝,簡單測試服務端如下
@Slf4j public class NioSslServer {public static void main(String[] args) throws Exception {NioSslServer sslServer = new NioSslServer("127.0.0.1", 8006);sslServer.start();// 使用 curl -vv -k 'https://localhost:8006' 連接}private SSLContext context;private Selector selector;public NioSslServer(String hostAddress, int port) throws Exception {// 初始化SSL Contextcontext = serverSSLContext();// 注冊監聽器selector = SelectorProvider.provider().openSelector();ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();serverSocketChannel.configureBlocking(false);serverSocketChannel.socket().bind(new InetSocketAddress(hostAddress, port));serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);}public void start() throws Exception {log.debug("等待連接中.");while (true) {selector.select();Iterator<SelectionKey> selectedKeys = selector.selectedKeys().iterator();while (selectedKeys.hasNext()) {SelectionKey key = selectedKeys.next();selectedKeys.remove();if (!key.isValid()) {continue;}if (key.isAcceptable()) {accept(key);} else if (key.isReadable()) {((SslSocketChannel)key.attachment()).read(buf->{});// 直接回應一個OK((SslSocketChannel)key.attachment()).write("HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n\r\nOK\r\n\r\n");((SslSocketChannel)key.attachment()).closeConnection();}}}}private void accept(SelectionKey key) throws Exception {log.debug("接收新的請求.");SocketChannel socketChannel = ((ServerSocketChannel)key.channel()).accept();socketChannel.configureBlocking(false);SslSocketChannel sslSocketChannel = new SslSocketChannel(context, socketChannel, false);if (sslSocketChannel.doHandshake()) {socketChannel.register(selector, SelectionKey.OP_READ, sslSocketChannel);} else {socketChannel.close();log.debug("握手失敗,關閉連接.");}} }以上:
SslSocketChannel測試客戶端
基于以上服務端封裝,簡單測試客戶端如下
@Slf4j public class NioSslClient {public static void main(String[] args) throws Exception {NioSslClient sslClient = new NioSslClient("httpbin.org", 443);sslClient.connect();// 請求 'https://httpbin.org/get'}private String remoteAddress;private int port;private SSLEngine engine;private SocketChannel socketChannel;private SSLContext context;/*** 需要遠程的HOST和PORT* @param remoteAddress* @param port* @throws Exception*/public NioSslClient(String remoteAddress, int port) throws Exception {this.remoteAddress = remoteAddress;this.port = port;context = clientSSLContext();engine = context.createSSLEngine(remoteAddress, port);engine.setUseClientMode(true);}public boolean connect() throws Exception {socketChannel = SocketChannel.open();socketChannel.configureBlocking(false);socketChannel.connect(new InetSocketAddress(remoteAddress, port));while (!socketChannel.finishConnect()) {// 通過REACTOR,不會出現等待情況//log.debug("連接中..");}SslSocketChannel sslSocketChannel = new SslSocketChannel(context, socketChannel, true);sslSocketChannel.doHandshake();// 握手完成后,開啟SELECTORSelector selector = SelectorProvider.provider().openSelector();socketChannel.register(selector, SelectionKey.OP_READ, sslSocketChannel);// 寫入請求sslSocketChannel.write("GET /get HTTP/1.1\r\n"+ "Host: httpbin.org:443\r\n"+ "User-Agent: curl/7.62.0\r\n"+ "Accept: */*\r\n"+ "\r\n");// 讀取結果while (true) {selector.select();Iterator<SelectionKey> selectedKeys = selector.selectedKeys().iterator();while (selectedKeys.hasNext()) {SelectionKey key = selectedKeys.next();selectedKeys.remove();if (key.isValid() && key.isReadable()) {((SslSocketChannel)key.attachment()).read(buf->{log.info("{}", new String(buf.array(), 0, buf.position()));});((SslSocketChannel)key.attachment()).closeConnection();return true;}}}} }以上:
總結
以上:
3 透明上游代理
透明上游代理相比透明代理要簡單,區別是
只需要對透明代理做以上簡單的修改,即可實現透明的上游代理。
4 非透明上游代理
非透明的上游代理,相比非透明的代理要復雜一些
以上,分為四個組件:客戶端,代理服務(ServerHandler),代理服務(ClientHandler),服務端
三 設計與實現
本文需要構建的是非透明上游代理,以下采用NETTY框架給出詳細的設計實現。上文將統一代理網關分為兩大部分,ServerHandler和ClientHandler,以下
1 代理網關服務端
主要包括
初始化代理網關服務
public void start() {HookedExecutors.newSingleThreadExecutor().submit(() ->{log.info("開始啟動代理服務器,監聽端口:{}", auditProxyConfig.getProxyServerPort());EventLoopGroup bossGroup = new NioEventLoopGroup(auditProxyConfig.getBossThreadCount());EventLoopGroup workerGroup = new NioEventLoopGroup(auditProxyConfig.getWorkThreadCount());try {ServerBootstrap b = new ServerBootstrap();b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).handler(new LoggingHandler(LogLevel.DEBUG)).childHandler(new ServerChannelInitializer(auditProxyConfig)).bind(auditProxyConfig.getProxyServerPort()).sync().channel().closeFuture().sync();} catch (InterruptedException e) {log.error("代理服務器被中斷.", e);Thread.currentThread().interrupt();} finally {bossGroup.shutdownGracefully();workerGroup.shutdownGracefully();}});}代理網關初始化相對簡單,
代理網關服務的請求處理器在 ServerChannelInitializer中定義為
@Overrideprotected void initChannel(SocketChannel ch) throws Exception {ch.pipeline().addLast(new HttpRequestDecoder()).addLast(new HttpObjectAggregator(auditProxyConfig.getMaxRequestSize())).addLast(new ServerChannelHandler(auditProxyConfig));}首先解析HTTP請求,然后做聚批的處理,最后ServerChannelHandler實現代理網關協議;
代理網關協議:
詳細實現為:
@Overridepublic void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {FullHttpRequest request = (FullHttpRequest)msg;try {if (isConnectRequest(request)) {// CONNECT 請求,存儲待處理saveConnectRequest(ctx, request);// 禁止讀取ctx.channel().config().setAutoRead(false);// 發送回應connectionEstablished(ctx, ctx.newPromise().addListener(future -> {if (future.isSuccess()) {// 升級if (isSslRequest(request) && !isUpgraded(ctx)) {upgrade(ctx);}// 開放消息讀取ctx.channel().config().setAutoRead(true);ctx.read();}}));} else {// 其他請求,判定是否已升級if (!isUpgraded(ctx)) {// 升級引擎upgrade(ctx);}// 連接遠程connectRemote(ctx, request);}} finally {ctx.fireChannelRead(msg);}}2 代理網關客戶端
代理網關服務端需要連接遠程服務,進入代理網關客戶端部分。
代理網關客戶端初始化:
/*** 初始化遠程連接* @param ctx* @param httpRequest*/protected void connectRemote(ChannelHandlerContext ctx, FullHttpRequest httpRequest) {Bootstrap b = new Bootstrap();b.group(ctx.channel().eventLoop()) // use the same EventLoop.channel(ctx.channel().getClass()).handler(new ClientChannelInitializer(auditProxyConfig, ctx, safeCopy(httpRequest)));// 動態連接代理FullHttpRequest originRequest = ctx.channel().attr(CONNECT_REQUEST).get();if (originRequest == null) {originRequest = httpRequest;}ChannelFuture cf = b.connect(new InetSocketAddress(calculateHost(originRequest), calculatePort(originRequest)));Channel cch = cf.channel();ctx.channel().attr(CLIENT_CHANNEL).set(cch); }以上:
代理網關客戶端的處理器的初始化邏輯:
@Overrideprotected void initChannel(SocketChannel ch) throws Exception {SocketAddress socketAddress = calculateProxy();if (!Objects.isNull(socketAddress)) {ch.pipeline().addLast(new HttpProxyHandler(calculateProxy(), auditProxyConfig.getUserName(), auditProxyConfig.getPassword()));}if (isSslRequest()) {String host = host();int port = port();if (StringUtils.isNoneBlank(host) && port > 0) {ch.pipeline().addLast(new SslHandler(sslEngine(host, port)));}}ch.pipeline().addLast(new ClientChannelHandler(clientContext, httpRequest));}以上:
四 其他問題
代理網關實現可能面臨的問題:
1 內存問題
代理通常面臨的問題是OOM。本文在實現代理網關時保證內存中緩存時當前正在處理的HTTP/HTTPS請求體。內存使用的上限理論上為實時處理的請求數量*請求體的平均大小,HTTP/HTTPS的請求結果,直接使用堆外內存,零拷貝轉發。
2 性能問題
性能問題不應提早考慮。本文使用NETTY框架實現的代理網關,內部大量使用堆外內存,零拷貝轉發,避免了性能問題。
代理網關一期上線后曾面臨一個長連接導致的性能問題,
使用IdleStateHandler定時監控空閑的TCP連接,強制關閉;解決了該問題。
五 總結
本文聚焦于統一代理網關的核心,詳細介紹了代理相關的技術原理。
代理網關的管理部分,可以在ServerHandler部分維護,也可以在ClientHandler部分維護;
最后,本文實現代理網關后,針對代理的資源和流經代理網關的請求做了相應的控制,主要包括:
原文鏈接
本文為阿里云原創內容,未經允許不得轉載。?
總結
以上是生活随笔為你收集整理的代理网关设计与实现(基于NETTY)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 当微服务遇上 Serverless |
- 下一篇: 基于MaxCompute SQL 的半结