JSON-RPC cross-language calls between Golang and Java

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

 about how to use Golang to call RPC and JSON-RPC, although there are a lot of posts online, but it is only Golang inter-program communication, there is no cross-language calls involved in the issue. When using Golang to develop a service-side program, it is unavoidable to interact with programs in other languages, especially the JSON-RPC protocol, which itself should be used on calls between different platforms (because the communication between Golang programs already has a closed RPC packet encoded with GOB codec. , we naturally think of using JSON-RPC to provide support for other languages. This article explores in detail how to implement the JSON-RPC call between Golang and Java.

    • First, implement a socket-based Java call Golang sample (this method does not require a third-party Golang library, but can only communicate through the TCP protocol. If you want to communicate through the HTTP protocol, you must write your own or use a third-party library, which will be described later)
Package Rpcz//First we create a simple Golang RPC server based on socketImport ("FMT"    "Net"    "Net/rpc"    "Net/rpc/jsonrpc") Type Counterstruct{Sumint}func ( This*counter) Add (iint, R *int) Error { This. Sum + =I*r = This. Sum FMT. Printf ("I:%v", i)returnNil}func newjsonrpcsocketserver () {RPC. Register (New(Counter)) L, err:= Net. Listen ("TCP",": 3333")    ifErr! =Nil {fmt. Printf ("Listener TCP err:%s", Err)return    }     for{fmt. Println ("wating ...") conn, err:=l.accept ()ifErr! =Nil {fmt. Sprintf ("Accept Connection err:%s\n", Conn)} Go jsonrpc. SERVECONN (conn)}}func Newjsonrpcsocketclient () {conn, err:= Net. Dialtimeout ("TCP","127.0.0.1:3333", +* +* +* -)    ifErr! =Nil {fmt. Printf ("Create client err:%s\n", Err)return} defer Conn. Close () Client:=Jsonrpc. Newclient (conn)varReplyintErr= client. Call ("Counter.add",Ten, &reply) fmt. Printf ("reply:%s, err:%s\n", reply, err)}

 The Newjsonrpcsocketserver () method above creates a TCP protocol-based JSON-RPC server, and the Newjsonrpcsocketclient () method demonstrates a simple call on the Golang side (note that TCP-based, Instead of the HTTP protocol! An HTTP protocol-based invocation method that invokes the "Github.com/gorilla/rpc/json" implementation is given later. But this is not the point, the following look at the Java client call, you can see that this is a socket-based communication:

 Packagecn;Importcom.googlecode.jsonrpc4j.JsonRpcClient;Importjava.io.IOException;ImportJava.io.InputStream;ImportJava.io.OutputStream;Importjava.net.*;/*** Created by geomantic on 15/8/21.*/ Public classsocketclient { Public Static voidMain (string[] args) {Try{Socket Socket=NewSocket ("127.0.0.1", 3333); Jsonrpcclient Client=Newjsonrpcclient (); InputStream IPs=Socket.getinputstream (); OutputStream Ops=Socket.getoutputstream (); intReply = Client.invokeandreadresponse ("Counter.add",NewOBJECT[]{1001},int.class, OPS, IPS); System.out.println ("Reply:" +reply); } Catch(IOException e) {e.printstacktrace (); } Catch(Throwable throwable) {throwable.printstacktrace (); }    }}

  The Java code above initially demonstrates how to invoke two very important constraints on the Golang server asynchronously:

  1. The method name registration and invocation of the Golang server are consistent in the format: struct name. The method name, such as the counter.add above.

2. The method that can be registered must satisfy the specified function signature:

func (t *t) MethodName (Argtype T1, Replytype *t2) error.

   There are only two entries, the first is the input parameter of the called function, and the second is the output parameter of the called function. The return value has only one error type. None of the three parameters can be changed.

But TCP-based calls, for people accustomed to the HTTP protocol will feel the pain of writing, perhaps more people are accustomed to using HTTP to parse. However, due to the relatively trivial details of the solution, and involved in some third-party library code modification, taking into account the length of the issue to prepare another, in the next article to demonstrate the implementation of the RPC protocol using HTTP implementations.

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: 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.