[英]Access running java program from shell command
I am looking for a way to access running java program from command line.我正在寻找一种从命令行访问正在运行的 java 程序的方法。 The best woud be something that does the following:
最好的方法是执行以下操作:
Starting java app:启动 java 应用程序:
bash$java -jar MyBundle.jar App
Accessing app:访问应用程序:
bash$test.sh param1 param2
So, test.sh
calls App
from MyBundle.jar
somehow and passes values param1
& param2
.因此,
test.sh
以某种方式从MyBundle.jar
调用App
并传递值param1
和param2
。
Important: I am looking for very fast approach.重要提示:我正在寻找非常快速的方法。
App
hold database connection and it is very expensive to start App
every time I need access do DB. App
保持数据库连接,每次我需要访问数据库时启动App
非常昂贵。
I need solution that will work in Ubuntu and Debian.我需要适用于 Ubuntu 和 Debian 的解决方案。 If it will work on Mac - great.
如果它可以在 Mac 上运行 - 太好了。
Any help is appreciated!任何帮助表示赞赏!
I think you need to take a client-server approach.我认为您需要采用客户端-服务器方法。 You app is the server, it runs as a background process and listens for connections on some port.
您的应用程序是服务器,它作为后台进程运行并侦听某个端口上的连接。 And your client makes requests to the server and gets back the response.
您的客户端向服务器发出请求并取回响应。
A fast and simple way of implementing this in java would be to wrap your app in the Jetty servlet container.在 java 中实现此功能的一种快速简单的方法是将您的应用程序包装在Jetty servlet 容器中。 You could set it up to return JSON responses for example, which are easy to process.
例如,您可以将其设置为返回 JSON 响应,这些响应易于处理。
It would be quite straightforward to open a TCP/IP socket and use netcat
from the shell.打开 TCP/IP 套接字并使用 shell 中的
netcat
将非常简单。
Java code Java码
final ServerSocket serverSocket = new ServerSocket(9050);
while (true) {
final Socket socket = serverSocket.accept();
java.util.logging.Logger.getAnonymousLogger().info("Accepted");
final BufferedReader br = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
final String input = br.readLine();
final BufferedWriter bw = new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream()));
bw.write("You said [" + input + "]");
bw.flush();
socket.close();
}
Shell code Shell代码
echo 'bla' | nc localhost 9050
You'd need to muck around with threads to keep the sockets open to serve multiple requests.您需要使用线程来保持 sockets 打开以服务多个请求。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.