如何在Go中使用Java

huangapple go评论115阅读模式
英文:

how to use java with go

问题

由于某种原因,我必须使用Go作为我的新Web项目的后端语言。

然而,我们将使用的一些API是用Java编写的,并打包在.jar文件中。

我对Go还不熟悉,我该如何以一种一致的方式使用Go与Java进行合作,使得当收到HTTP请求时,Go将处理它并将一些功能委托给Java,然后返回响应。

英文:

For some reason, I have to use go as my new web project's backend language.

However, some apis we will use is written in Java and packaged in .jar file.

I am new to go, and how can I use go to cooperate with Java in a consistent way that when a HTTP request comes, the go will handle it and delegate some function to java, and then return the response.

答案1

得分: 14

如果您的Java代码暴露了一个RPC API,您可以使用Go的json-rpc模块。

如果您的Java代码暴露了一个RESTful API,您可以使用Go的http模块。

您还可以生成一个子进程(您的Java代码),并通过标准输入和标准输出管道与其通信。您可以使用exec模块来实现这一点。

这并不是一个详尽无遗的通信列表,只是我能想到的前三种方法。您还可以使用XML API、共享内存或命名管道。

此外,像0mq这样的消息队列可能是您正在寻找的。0mq处理了许多IPC的复杂部分,比如在接收者过载时使发送者停止发送请求、消息分帧以及在失败后重新连接。

在Java代码和Go代码之间有很多种通信方式。我认为最常见和简单的方式是通过HTTP API进行通信。在Java服务器中暴露一个RESTful或RPC API,将其作为HTTP API服务运行,编写Go代码来处理传入的HTTP请求,然后从Go代码连接到Java API以帮助创建响应。

英文:

What kind of API does your Java expose?

If it exposes an RPC API you could utilize <a href="http://golang.org/pkg/net/rpc/jsonrpc/">Go's json-rpc module</a>.

If it exposes a RESTful API you could utilize <a href="http://golang.org/pkg/net/http/">Go's http module.</a>

You could also spawn a child process (your java code) and talk to it via stdin and stdout pipes. You'd use the <a href="http://golang.org/pkg/os/exec/">exec module</a> for that.

That's not an exhaustive communication list, just the first three that come to mind. You could also use an XML API, shared memory or named pipes.

Also, a message queue like <a href="http://www.zeromq.org/">0mq</a> might be what you're looking for. 0mq handles a lot of the tricky bits of IPC, like making senders back off sending requests if the receiver is getting overloaded, message framing, and reconnecting after failure.

There are numerous ways you could communicate between your Java code and your Go code. I think in the end it's most common and simple to do so via HTTP API. Expose a RESTful or RPC API in a Java server, run it as an HTTP API service, write your Go to handling incoming HTTP requests and then connect with the Java API from Go to assist in creating a response.

huangapple
  • 本文由 发表于 2012年12月27日 10:31:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/14048699.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定