Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use CountDownLatch to realize BIO based on netty

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

Today, I will talk to you about how to use CountDownLatch to achieve netty-based BIO. Many people may not know much about it. In order to make you understand better, the editor has summarized the following content for you. I hope you can get something according to this article.

Netty is a NIO client-server framework. In NIO mode, the thread returns the result directly, and then the asynchronous thread calls back the client message processing after the buffer is ready. It does not block threads like BIO and continues to wait for the callee to prepare the response data before returning.

However, in some scenarios where socket communication is used, NIO's netty is used, but the caller must wait for the service to return to the business processing state before performing subsequent operations, so the BIO pattern is needed. In addition to using java's native BIO, here is an implementation that uses CountDownLatch+Netty to simulate BIO.

The implementation process and pseudo code are described below, and the complete sample download address is provided at the end of the article. The code is for learning only.

Environment: netty4.1.27, eclipse,jdk1.8

Process design

Principle explanation

1. When the client sends data to the server (which is simply implemented by java native socket in this example), the unique ID (sn) of the request sent is generated through uuid, and the sn is attached to the header of the sent data (this sn is required when the server returns). At the same time, the client generates a CountDownLatch and the current sn binding.

2. After it is successfully sent, the current thread is blocked through CountDownLatch.await.

3. After the server receives the data and processes the relevant data, it encapsulates the returned data with the client sn and sends it to the client. After receiving the information returned by the server, the client receives the corresponding CountDownLatch according to the returned sn, and calls countDown to enable the thread blocked in the previous step to continue with subsequent business operations.

Key code snippet

Send a message

/ * send message * @ param msg*/public void sendMsg (String ip,int port,String msg) {try {/ / 1 connects to the server, if the persistent connection can modify this logical connectToServer (ip, port); / / 2 generate the blocking counter String sn = UUID.randomUUID (). ToString (); Receiver.addWait (sn) / / 3 send data client.channel (). WriteAndFlush (sn+ "@" + msg+ "END") .sync (); / / add end to prevent sticking LOG.info ("send message successfully, msg:" + msg); / / 4 wait for the counter countdown after receiving the message. Receiver.block (sn); / / you can set the wait time to prevent threads from blocking for a long time. / / 5 the processing server returned handlerServerAnswer (sn);} catch (Exception e) {LOG.error ("failed to process messages.", e);}}

Receive messages

/ * Overridepublic void channelRead (ChannelHandlerContext ctx, Object msg) throws Exception {try {String dataFromServer = (String) msg; String [] snData = dataFromServer.split ("@"); String sn = snData [0]; String data = snData [1]; response.put (sn, data); / / waiting for business logic to consume if (! waitLatch.containsKey (sn)) {LOG.error ("illegal sn:" + sn) Return;} waitLatch.get (sn). CountDown (); / / unblock and let the sending thread run logic later. WaitLatch.remove (sn);} catch (Exception e) {LOG.error ("illegal data received:" + msg);}}

Server code

/ * Analog server * @ param args* @ throws Exception*/public static void main (String [] args) throws Exception {serverSocket = new ServerSocket (PORT); LOG.info ("Service snooping starts, port:" + PORT); while (true) {try {Socket socket = serverSocket.accept (); InputStream in = socket.getInputStream (); int len; StringBuffer sb = new StringBuffer () Byte [] bytes = new byte [1024]; while ((len = in.read (bytes))! =-1) {String bytesData = new String (bytes,0,len, "utf-8"); sb.append (bytesData); if (bytesData.endsWith ("END")) {/ / processes the business logic and returns the message handMsgAndResponse (socket,sb.toString ()) Sb = null;} catch (Exception e) {LOG.error ("failed to process client messages.", e);} Thread.sleep (1000);}} after reading the above, do you have any further understanding of how to use CountDownLatch to implement netty-based BIO? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report