虚拟机间通讯 [英] inter jvm communication
问题描述
我正在寻找Java中的进程间通信库.我希望在JVM之间发送小消息,并且如果可以的话,我希望使用共享内存来完成它.
I am looking for an inter-process communication library in Java. I am looking to send small messages between JVMs and would like to do it using shared memory if I could.
推荐答案
Java NIO支持内存映射文件.如果多个JVM内存映射同一个文件,则可以将其用作共享内存.
Java NIO has support for memory-mapped files. If multiple JVMs memory-map the same file they can use it as shared memory.
这是一个内存映射文件的示例.
Here is an example of memory mapping a file.
try {
int shmSize = 1024;
RandomAccessFile file = new RandomAccessFile("shm.raw","rw");
// inialize file size
if(file.length() < shmSize) {
byte[] tmp = new byte[shmSize];
file.write(tmp);
file.seek(0); // seek back to start of file.
}
// memory-map file.
FileChannel ch = file.getChannel();
MappedByteBuffer shm = ch.map(FileChannel.MapMode.READ_WRITE, 0, shmSize);
ch.close(); // channel not needed anymore.
shm.load(); // force file into physical memory.
// now use the ByteBuffer's get/put/position methods to read/write the shared memory
} catch(Exception e) { e.printStackTrace(); }
在Linux上,您可以在/dev/shm/基于内存的文件系统中创建shm.raw文件.这将有助于避免任何磁盘I/O.
On Linux you can create the shm.raw file in /dev/shm/ a memory based filesystem. This will help avoid any disk I/O.
有关更多详细信息,请阅读本文 Java中的内存映射IO简介
For more details read this article Introduction to Memory-Mapped IO in Java
此外,您仍然需要一种将读取/写入同步到共享内存的方法.写完完整的消息后,发送方JVM将需要向接收方JVM发信号.
Also you will still need a way to syncronize read/writes to the shared memory. The sender JVM will need to signal the receiver JVM when a complete message has been written.
对于小消息,使用Java NIO的SocketChannel可能更好,因为可以在接收到消息时通知接收者.共享内存仅在发送大型邮件时真正有用.
Using Java NIO's SocketChannel might be better for small messages since the receiver can be notified when a message is received. Shared memory will only really help when sending large messages.
对于不同机器上的JVM之间的IPC,请尝试 JIPC
For IPC between JVMs on different machines try JIPC
这篇关于虚拟机间通讯的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!