How a simple RPC framework is refined (IV)--Implementing the codec for RPC messages

Source: Internet
Author: User

Before we developed a very simple RPC message format, but also left two problems, the last one to solve the missing one, but also left a

we have not implemented the corresponding encode and decode methods, not based on the transmission of strings across devices, but direct memory variable delivery. the request command with parameters is not supported by RPC request now. such as Add (A, b), how to describe parameter A,b in RPC messages. Let's get rid of the codec. The actual RPC application is basically a cross machine connection, so it is not possible to pass the memory variables directly, that is, you also need to encode the message into something such as a string that can be transferred across the device. There are many encapsulation protocols for specific RPC messages, often based on Xml,json encapsulation. But if it's abstract, it's actually a codec, which is what you encode, which is not coded. Black Cat, White cat, as long as can pass, is a good cat.
Here I still simple principle, focus on Yu Xiaoyi. Take advantage of two operations in Python. Str and eval.         Suppose a dictionary msg = {' A ': 1, ' B ': 2}. So str (msg) = "{' A ': 1, ' B ': 2}", notice becomes a string.         Then eval ("{' A ': 1, ' B ': 2}")-->msg, makes an eval operation, and then becomes a dictionary variable from the string.          When encoded, the RPC message is first converted to Dict, and then the STR is encoded as a string. When decoding, first call eval to get the Dict object and then convert to a specific RPC message object
The design has been set, the rest is just code filling. First revise the Str method of the original request, and return a dict string representation. Do the same with response.

Class Request (object):
    def __str__ (self): return
        str ({' id ': self.id,  ' command ': Self.command, ' Parameter ': Self.parameter})

Then introduce the Encode method
    @classmethod
    def encode (CLS, message):
        if isinstance (message, Request): Return
            str
        elif Isinstance (Message, Response): Return
            STR (message)
        elif isinstance (Message, Notification): Return
            str ( Message)
        else:
            raise Exception (' unknown type when encode ')

Similarly, the introduction of the Decode method is slightly more complex. The main trouble is how to distinguish between decoding is response or request my approach is more speculative, directly based on the contents of the dictionary to judge. The command field must be the request, the result field is definitely response
@classmethod    
    def decode (CLS, data):
        info = eval (data)
        if ' command ' in info:
            request = Request ()
            Request.id = info.get (' id ')
            request.command = info.get (' command ') 
            request.parameter = info.get (' parameter ', { Return
            request
        elif ' result ' in info:
            response = response ()
            response.id = info.get (' id ')
            Response.result = info.get (' result ') return
            response
        elif ' message ' in info: note
            = Notification ()
            note.message = info.get (' message ') return
        Note else:
            raise Exception (' unknown data when Decode ')

In addition, the client and server code also need to adjust slightly, that is very simple, call the above method is OK, here is not posted. OVER,RPC News This piece, we completely finished. Summary: The definition of request and resonse can be constant, encode and decode methods, such as Sun Dasan, can be ever-changing. If you use XML or JSON or other descriptions, as long as the custom encode and decode methods can be viewed from a higher level, the RPC message is actually a description of the function call, so the view is at best. Since it is view, the actual degree of freedom is very large.

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: info-contact@alibabacloud.com 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.