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 realize netty and apply it to gmq

2025-02-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly explains "how to implement and apply netty to gmq". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Now let the editor take you to learn "how to implement and apply netty to gmq"!

I. background

Book connected to the above handwritten MQ framework (3)-client implementation, the previous implementation of the mq server and client in the form of web, now plans to use netty to transform it. I learned how to use netty some time ago. I probably have some ideas.

Netty encapsulates the use of socket, and we can build high-performance network applications through simple calls. I plan to use the following example to transform gmq.

What is netty?

Netty is an open source java framework provided by JBOSS. Netty provides asynchronous, event-driven network application framework and tools for the rapid development of high-performance, high-reliability network servers and client programs.

Netty is a java framework and a network programming framework that supports asynchronous and event-driven features, so it performs well.

3. Simple implementation of netty 1. Server 1) SimpleServerHandler

Handler is the processor, and handler is generated by Netty to handle the Imax O event.

Package me.lovegao.netty.learnw3c.mqdemo;import io.netty.channel.Channel;import io.netty.channel.ChannelHandlerContext;import io.netty.channel.SimpleChannelInboundHandler;import io.netty.channel.group.ChannelGroup;import io.netty.channel.group.DefaultChannelGroup;import io.netty.util.concurrent.GlobalEventExecutor;public class SimpleServerHandler extends SimpleChannelInboundHandler {public static ChannelGroup channels = new DefaultChannelGroup (GlobalEventExecutor.INSTANCE); @ Override public void handlerAdded (ChannelHandlerContext ctx) throws Exception {Channel incoming = ctx.channel () System.out.println ("[SERVER] -" + incoming.remoteAddress () + "join\ n"); channels.add (ctx.channel ());} @ Override public void handlerRemoved (ChannelHandlerContext ctx) throws Exception {Channel incoming = ctx.channel (); System.out.println ("[SERVER] -" + incoming.remoteAddress () + "leave\ n"); channels.remove (ctx.channel ()) } @ Override protected void channelRead0 (ChannelHandlerContext ctx, String s) throws Exception {Channel incoming = ctx.channel (); System.out.println ("[" + incoming.remoteAddress () + "]" + s); if (s = = null | | s.length () = 0) {incoming.writeAndFlush ("the message is empty! \ n ");} else {/ / MqRouter mqRouter = JSONObject.parseObject (s, MqRouter.class); / / System.out.println (mqRouter.getUri ()); String responseMsg =" received, + s + "\ n"; incoming.writeAndFlush (responseMsg);} @ Override public void channelActive (ChannelHandlerContext ctx) throws Exception {Channel incoming = ctx.channel () System.out.println ("SimpleChatClient:" + incoming.remoteAddress () + "online");} @ Override public void channelInactive (ChannelHandlerContext ctx) throws Exception {Channel incoming = ctx.channel (); System.out.println ("SimpleChatClient:" + incoming.remoteAddress () + "dropped");} @ Override public void exceptionCaught (ChannelHandlerContext ctx, Throwable cause) throws Exception {Channel incoming = ctx.channel () System.out.println ("SimpleChatClient:" + incoming.remoteAddress () + "exception"); cause.printStackTrace (); ctx.close ();}} 2) SimpleServerInitializer

SimpleServerInitializer is used to add multiple processing classes to ChannelPipeline, including encoding, decoding, SimpleServerHandler, etc.

Package me.lovegao.netty.learnw3c.mqdemo;import io.netty.channel.ChannelInitializer;import io.netty.channel.ChannelPipeline;import io.netty.channel.socket.SocketChannel;import io.netty.handler.codec.DelimiterBasedFrameDecoder;import io.netty.handler.codec.Delimiters;import io.netty.handler.codec.string.StringDecoder;import io.netty.handler.codec.string.StringEncoder;public class SimpleServerInitializer extends ChannelInitializer {@ Override protected void initChannel (SocketChannel ch) throws Exception {ChannelPipeline pipeline = ch.pipeline () Pipeline.addLast ("framer", new DelimiterBasedFrameDecoder (8192, Delimiters.lineDelimiter ()); pipeline.addLast ("decoder", new StringDecoder ()); pipeline.addLast ("encoder", new StringEncoder ()); pipeline.addLast ("handler", new SimpleServerHandler ()); System.out.println ("SimpleChatClient:" + ch.remoteAddress () + "Connect");}} 3) SimpleServerpackage me.lovegao.netty.learnw3c.mqdemo Import io.netty.bootstrap.ServerBootstrap;import io.netty.channel.ChannelFuture;import io.netty.channel.ChannelOption;import io.netty.channel.EventLoopGroup;import io.netty.channel.nio.NioEventLoopGroup;import io.netty.channel.socket.nio.NioServerSocketChannel;public class SimpleServer {private int port; public SimpleServer (int port) {this.port = port;} public void run () throws Exception {EventLoopGroup bossGroup = new NioEventLoopGroup (); EventLoopGroup workerGroup = new NioEventLoopGroup () Try {ServerBootstrap b = new ServerBootstrap (); b.group (bossGroup, workerGroup) .channel (NioServerSocketChannel.class) .childHandler (new SimpleServerInitializer ()) .option (ChannelOption.SO_BACKLOG, 128) .childOption (ChannelOption.SO_KEEPALIVE, true); System.out.println ("SimpleChatServer started"); ChannelFuture f = b.bind (port). Sync () F.channel (). CloseFuture (). Sync ();} finally {workerGroup.shutdownGracefully (); bossGroup.shutdownGracefully (); System.out.println ("SimpleChatServer is closed");}} public static void main (String [] args) throws Exception {int port If (args.length > 0) {port = Integer.parseInt (args [0]);} else {port = 8080;} new SimpleServer (port) .run ();}} 2, client 1) SimpleClientHandlerpackage me.lovegao.netty.learnw3c.mqdemo;import io.netty.channel.ChannelHandlerContext;import io.netty.channel.SimpleChannelInboundHandler Public class SimpleClientHandler extends SimpleChannelInboundHandler {@ Override protected void channelRead0 (ChannelHandlerContext ctx, String s) throws Exception {System.out.println ("received message:" + s);}} 2) SimpleClientInitializerpackage me.lovegao.netty.learnw3c.mqdemo;import io.netty.channel.ChannelInitializer;import io.netty.channel.ChannelPipeline;import io.netty.channel.socket.SocketChannel;import io.netty.handler.codec.DelimiterBasedFrameDecoder;import io.netty.handler.codec.Delimiters;import io.netty.handler.codec.string.StringDecoder Import io.netty.handler.codec.string.StringEncoder;public class SimpleClientInitializer extends ChannelInitializer {@ Override protected void initChannel (SocketChannel ch) throws Exception {ChannelPipeline pipeline = ch.pipeline (); pipeline.addLast ("framer", new DelimiterBasedFrameDecoder (8192, Delimiters.lineDelimiter ()); pipeline.addLast ("decoder", new StringDecoder ()); pipeline.addLast ("encoder", new StringEncoder ()); pipeline.addLast ("handler", new SimpleClientHandler ()) }} 3) SimpleClientpackage me.lovegao.netty.learnw3c.mqdemo;import java.io.BufferedReader;import java.io.InputStreamReader;import io.netty.bootstrap.Bootstrap;import io.netty.channel.Channel;import io.netty.channel.EventLoopGroup;import io.netty.channel.nio.NioEventLoopGroup;import io.netty.channel.socket.nio.NioSocketChannel;public class SimpleClient {private final String host; private final int port; public SimpleClient (String host, int port) {this.host = host This.port = port;} public static void main (String [] args) throws Exception {new SimpleClient ("localhost", 8080). Run ();} public void run () throws Exception {EventLoopGroup group = new NioEventLoopGroup () Try {Bootstrap bootstrap = new Bootstrap () .group (group) .channel (NioSocketChannel.class) .handler (new SimpleClientInitializer ()); Channel channel = bootstrap.connect (host, port). Sync (). Channel (); BufferedReader in = new BufferedReader (new InputStreamReader (System.in)) While (true) {String line = in.readLine (); if (line.equals ("exit!")) {break;} channel.writeAndFlush (line + "\ r\ n");} catch (Exception e) {e.printStackTrace () } finally {group.shutdownGracefully ();}} 3. Some things in learning

When I slightly changed the code on the tutorial, I found that the client could send a message, the server could receive the message, and the server also went to the process of replying to the client, but the client could not receive the message. It is normal to restore the code. After thinking about it for a long time, I finally found that the "\ n" flag was omitted when changing the code, resulting in the client never printing the message.

4. How to apply netty to gmq 1. What are the problems with its application

Netty only encapsulates the network interaction, gmq as a whole uses the gmvc framework, and the gmvc framework can not be separated from servlet. And I don't really want to change all the code I wrote before to my own new way.

2. Solution

1) transform the gmvc framework

Refactoring the gmvc framework to make it possible to break away from servlet use. That is, peel off the IOC function.

Advantages: one step in place, in line with the overall planning.

Cons: gmq iterations are delayed for some time.

2) temporarily abandon the gmvc framework

Temporarily remove the current dependent gmvc framework and give priority to completing the gmq iteration. The transformation will be carried out after the completion of the transformation of the gmvc frame in the later stage.

Advantages: can complete the function of gmq as soon as possible.

Disadvantages: remove the frame first, and then put it on later, which is equivalent to doing extra work twice. It takes time and effort.

At this point, I believe you have a deeper understanding of "how to achieve and apply netty to gmq". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

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

Development

Wechat

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

12
Report