Using Dotnetty to implement a Redis console application

Source: Internet
Author: User
Tags redis server

0: Demo run out of the results explained

The left-hand Blue command-line interface in the figure is linked with the Windows PowerShell command line.

1. Open the PowerShell command line interface and enter the command "telnet 6379".

If you do not have PowerShell, you can also use the CMD command line interface to test the effect of the Redis command.

Enter the ping command, and Redis receives it, which returns a Pong string. The purpose of the command is usually to test whether the connection to the server is still in effect. ping command

Entering the info command, Redis returns a large string of information on the Redis server. This command, which is used primarily to test the unpacking situation, describes how the unpacking is handled.

The command-line interface on the right-hand side of the diagram is the console application that the demo ran out of.

Two results A comparison, test out, our demo has got the correct results.

Ok, let's get into the play.

What's a dotnetty?

Dotnetty is a C # version of Netty.

Netty is a Java open source framework provided by JBoss. Netty provides asynchronous, event-driven network application frameworks and tools for rapid development of high-performance, high-reliability network servers and client programs. "Excerpt from Baidu Encyclopedia"

The author thinks that Netty is an important component of the Java Ecological Circle.

Native socket programming, high learning costs, using the original socket to do the project, that is, driving a green leather train, moving times dozen times ....

Using Netty to do projects, the development efficiency is undoubtedly a high-speed rail-like existence.

And it's hard to use native socket programming.

Two, write the cause of this demo

Study Dotnetty for a long time. Version 0.4 from Dotnetty. To the current version of 0.48. Implement a C/s side of your own example. There is no such thing as a good idea to achieve.

Today saw Haifeiwu "Netty source code in the implementation of the Redis protocol, and then want to follow the realization of A."

So, today's demo.

Yes, it's just a demo. does not replace Stackexchange.redis.

Third, learn about the Redis protocol

RESP is shorthand for the Redis serialization protocol. It is an intuitive text protocol that has the advantage of being very simple to implement and excellent in parsing performance.

The Redis protocol divides the transferred structure data into 5 minimum cell types, with the end of the unit being uniformly coupled with a carriage return line symbol \ r \ n, to indicate the end of the cell.

The single-line string begins with A + sign.

A multiline string begins with a $ symbol followed by a string length.

Integer values begin with the: symbol, followed by the string form of an integer.

The error message begins with the-symbol.

The array begins with a * number followed by the length of the array.

Specific introduction to the RESP protocol interested partners please step into the Haifeiwu another article Redis protocol specification (translated)

The above 2nd is the introduction from Haifeiwu

Four Demo code

1, defining enumeration Redismessagetype

1 Internal enumRedismessagetype:byte2     {3         /// <summary>4         ///single-line string starting with +5         /// </summary>6Simplestring = +,7 8         /// <summary>9         ///error message with-startTen         /// </summary> OneError = $, A         /// <summary> -         ///integer data integer starting with: -         /// </summary> theInteger = -, -         /// <summary> -         ///multi-line string starting with $ -         /// </summary> +Bulkstring = $, -  +         /// <summary> A         ///array starting with a * at         /// </summary> -Arrayheader = the -}
View Code

2, define the Redisobject and define the virtual method WriteBuffer

1  Public classRedisobject2     {3          Public Virtual voidWriteBuffer (ibytebuffer output)4         {5         }6     }7 8  Public classRediscommon:redisobject9     {Ten          PublicRediscommon () One         { ACommond =Newlist<string>(); -         } -          Publiclist<string> Commond {Get;Set; } the          Public Override voidWriteBuffer (ibytebuffer output) -         { -             //Request Header format, *<number of arguments>\r\n -             //Const string HEADSTR = "*{0}\r\n"; +             //parameter information $<number of bytes of argument n>\r\n<argument data>\r\n -             //Const string BULKSTR = "${0}\r\n{1}\r\n"; +StringBuilder StringBuilder =NewStringBuilder (); AStringbuilder.appendformat ("*{0}\r\n", commond.count); at             foreach(varIteminchCommond) -             { -Stringbuilder.appendformat ("${0}\r\n{1}\r\n", item. Length,item); -             } -             //*1\r\n$4\r\nping\r\n -             byte[] bytes =Encoding.UTF8.GetBytes (stringbuilder.tostring ()); in output. Writebytes (bytes); -         } to}
View Code

3, defines the Redisencoder encoder, which integrates the Messagetobyteencoder<t> method. The main is to Redisobject, write to Ibytebuffer inside.

public class redisencoder:dotnetty.codecs.messagetobyteencoder<redisobject>    {        protected override void Encode (Ichannelhandlercontext context, Redisobject message, Ibytebuffer output)        {            message. WriteBuffer (output);            Context. Writeandflushasync (output);        }    }


4, defines the Redisdecoder decoder, which inherits the Bytetomessagedecoder.

Bytetomessagedecoder is the need to implement their own solution to the sticky bag, unpacking. Relatively low level, but flexible.

Dotnetty also has other high-level decoders.

Like Messagetomessagedecoder, Datagrampacketdecoder,lengthfieldbasedframedecoder,linebasedframedecoder, Replayingdecoder,delimiterbasedframedecoder,stringdecoder.

In Li Linfeng Teacher's "Netty authoritative guide" a book, can learn.

Passing the test, we learned that the info command returned a multi-line string

Begins with the $ sign followed by the string length. Assuming that the Redis server is returning a multiline string, its return format is: ${string length}\r\n{string}\r\n

The code for parsing a multiline string is


        Private stringreadmultiline (Ibytebuffer input) {Int64 strlength=Readinteger (input); Int64 Packlength= input. Readerindex + strlength +2; //the length of the package is larger than the actual package, skipping over him and preventing stacking            if(Input. Writerindex>packlength) {input. Skipbytes (input.            Readablebytes); }            if(Strlength = =-1)            {                return NULL; }            //package length, smaller than actual package unpacking            if(Packlength >input. Writerindex) {Throw NewException (""); }            intCount =0; intWhildcount =0; StringBuilder StringBuilder=NewStringBuilder ();  while(input. IsReadable ()) {stringStr= This.                ReadString (input); Count+=Str.                Length;                Stringbuilder.appendline (str); Whildcount++; }

returnstringbuilder.tostring (); }

6. Defining Redishandle Handler, he inherited the Simplechannelinboundhandler method. The Redisobject object to be solved after receiving the decoder.

public class redishandle:simplechannelinboundhandler<redisobject>    {        protected override void ChannelRead0 (Ichannelhandlercontext ctx, Redisobject msg)        {            if (msg is reidsstring)            {                reidsstring reidsstring = (reidsstring) msg;                Console.WriteLine (reidsstring.content);}}}    

Conclusion: Attach Source Address


Thank you for the review of this article, and suggest changes

Using Dotnetty to implement a Redis console application

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.