Java RMI (Remote Method Invocation) is a technology that allows communication and interaction between Java virtual machines. It allows remote Java objects to be accessed and manipulated like local objects, thus simplifying the development of distributed applications. Some applications will still use RMI to achieve communication and interaction , today's content we talk about RMI things.
I. First, let's understand the concept
RMI Principles
The basic idea of RMI is remote method invocation. When a client invokes a remote method, it actually sends a call request to the server, which executes the method and returns the result to the client.RMI implements remote invocation by means of the Stub and Skeleton classes, with the Stub located on the client side and the Skeleton on the server side.
RMI component
-
remote interface: must be inherited from
interface, and declares that it throws the
RemoteException
。 - remote object: Classes that implement the remote interface.
- RMI server: Provides remote objects and handles client invocation requests.
- RMI client: Initiate a remote method call request.
- Registration Service (Registry): Provides service registration and acquisition, similar to a directory service.
uplink
RMI uses the Java serialization mechanism to pass data. The client serializes the method parameters and sends them over the network to the server, which deserializes the parameters and executes the remote method, then serializes the result back to the client.
RMI Case
The following is a simple RMI example, including both server and client implementation ideas, which will be explained in code again in the following section:
server-side
- Implement a remote interface, for example
PersonController
, which contains a remote methodqueryName
。 - Create a concrete implementation class of this interface
PersonControllerImpl
and implement remote methods in it. - In the server's
main
method, instantiate the remote object, create the RMI registry, and use theBinds the remote object to the specified name.
client (computing)
- pass (a bill or inspection etc)
method to get the stub of the remote object using the name provided by the RMI registry.
- Calling a method on a stub, like calling a local method, is actually calling a remote method on the server.
Limitations of RMI
- language restriction: RMI is a Java-specific technology and cannot be used directly in non-Java applications.
- Security issues: The serialization mechanism of RMI may pose a security risk and it is not recommended to expose port 1099 to the public network.
- Performance and Scalability: The performance of RMI is affected by network latency and bandwidth, and may face scalability limitations in highly concurrent situations.
Application Scenarios for RMI
RMI is suitable for the need for remote communication between Java programs in the scene , such as distributed banking systems , game servers , stock trading systems and online shopping malls and so on. Next together with a simple case to use it .
II. Use of cases
Let's first get a simple case of Java RMI server-side and client-side implementation. In this case, the server-side will provide a file namedHelloWorld
remote service, the client will call this service and print the returned greeting.
Server-side implementation
-
Defining the Remote Interface:
This interface is required by both the server and the client. It must inherit from theinterface, and all remote methods are declared to throw the
RemoteException
。
import ;
import ;
public interface HelloWorld extends Remote {
String sayHello() throws RemoteException;
}
-
Implementing Remote Interfaces:
Create a class that implements the above interface and implement the remote methods.
import ;
import ;
public class HelloWorldImpl extends UnicastRemoteObject implements HelloWorld {
protected HelloWorldImpl() throws RemoteException {
super();
}
@Override
public String sayHello() throws RemoteException {
return "Hello, World!";
}
}
-
Setting up the RMI server:
Create a main class to set up the RMI server, binding remote objects to the RMI registry.
import ;
import ;
import ;
public class HelloWorldServer {
public static void main(String[] args) {
try {
// Create the remote object
HelloWorld helloWorld = new HelloWorldImpl(); // Get a reference to the RMI registry and create or get a registry instance on the specified port.
// Get a reference to the RMI registry and create or get a registry instance on the specified port
(1099); // Get a reference to the RMI registry and create or fetch a registry instance on the specified port.
// Bind the remote object to the RMI registry, and the client can access the remote object by this name
("rmi://localhost/HelloWorld", helloWorld); // Bind the remote object to the RMI registry, and the client can access the remote object by that name.
("HelloWorld RMI object bound"); }
} catch (Exception e) {
("Server exception: " + ()); ("Server exception: " + ()); ("Server exception: " + ())
(); } catch (Exception e) { ("Server exception: " + ()); }
}
}
}
Client-side implementation
-
Calling Remote Services:
The client uses the name of the RMI registry to look up the remote object and invoke its methods.
import ;
import ;
public class HelloWorldClient {
public static void main(String[] args) {
try {
// utilizationRMIFind remote objects by registry name
HelloWorld helloWorld = (HelloWorld) ("rmi://localhost/HelloWorld");
// Calling remote methods
String response = ();
("Response: " + response);
} catch (Exception e) {
("Client exception: " + ());
();
}
}
}
Let's explain it in detail.
-
remote interface (
HelloWorld
): This is the protocol for communication between the server and the client. It defines methods that can be called remotely. -
Remote Object Implementation (
HelloWorldImpl
): This is an implementation of the Remote Interface.RMI calls actually invoke methods from this implementation. -
server (computer) (
HelloWorldServer
): Responsible for creating an instance of the remote object and binding this instance to the RMI registry. This allows the client to access the object by the name of the registry. -
client (computing) (
HelloWorldClient
): Use the name of the RMI registry to look up a remote object on the server and call its methods.
Next you can compile all the class files, run the server-side program, make sure that the RMI registry has been started (in some versions of Java will automatically start), and then run the client program, done. Note that since RMI uses Java serialization, the client and server class paths must be consistent or compatible.
III. Application of RMI in Distributed Banking Systems
Next, V is going to introduce the application in business scenarios. Take in a distributed banking system, we can use RMI to realize the communication between different bank branches, for example, to realize the operation of querying and transferring account information. The following is a simplified example, which includes two basic operations: inquiring about account balances and performing transfers, follow the steps step by step.
Step 1: Define the Remote Interface
First, define a remote interfaceBankService
It will be realized by individual branches to provide banking services.
import ;
import ;
public interface BankService extends Remote {
double getAccountBalance(String accountNumber) throws RemoteException;
boolean transferFunds(String fromAccount, String toAccount, double amount) throws RemoteException;
}
Step 2: Implement the Remote Interface
Next, implement this interface to create the remote object that will provide the actual banking service.
import ;
import ;
import ;
import ;
public class BankServiceImpl extends UnicastRemoteObject implements BankService {
private Map<String, Double> accounts = new HashMap<>();
protected BankServiceImpl() throws RemoteException {
super();
// Initialize some account information
("123456789", 5000.00);
("987654321", 1000.00);
}
@Override
public double getAccountBalance(String accountNumber) throws RemoteException {
return (accountNumber, 0.00);
}
@Override
public boolean transferFunds(String fromAccount, String toAccount, double amount) throws RemoteException {
if ((fromAccount) && (fromAccount) >= amount) {
(fromAccount, (fromAccount) - amount);
(toAccount, amount, Double::sum);
return true;
}
return false;
}
}
Step 3: Setting up the RMI server
The server side will createBankService
of the remote object instance and bind it to the RMI registry.
import ;
import ;
import ;
public class BankServer {
public static void main(String[] args) {
try {
(1099); // establishRMIregistration form
BankService bankService = new BankServiceImpl();
("//localhost/BankService", bankService); // Binding Remote Objects
("BankService is ready for use.");
} catch (Exception e) {
("Server exception: " + ());
();
}
}
}
Step 4: Implement the RMI Client
The client will use the name of the RMI registry to find the remote object and invoke its methods.
import ;
import ;
import ;
public class BankClient {
public static void main(String[] args) {
try {
BankService bankService = (BankService) ("//localhost/BankService");
("Account balance: " + ("123456789"));
// Perform a transfer operation
boolean isTransferSuccess = ("123456789", "987654321", 200.00);
if (isTransferSuccess) {
("Transfer successful.");
} else {
("Transfer failed.");
}
// Re-check Balance
("New account balance: " + ("123456789"));
} catch (RemoteException | NotBoundException e) {
("Client exception: " + ());
();
}
}
}
Let's explain it in detail.
-
remote interface (
BankService
): defines two methods:getAccountBalance
for checking account balances.transferFunds
Used to perform transfer operations. -
Remote Object Implementation (
BankServiceImpl
): implements theBankService
interface. It uses aHashMap
to simulate account and balance information. -
server (computer) (
BankServer
): The RMI server is set up and willBankService
implementation is bound to the RMI registry for client access. -
client (computing) (
BankClient
): Look in the RMI registry for theBankService
service and call its methods to check balances and perform transfers.
After jacking up the code, compile all the class files and run the server-side programBankServer
Then run the client program.BankClient
Test the effect.
ultimate
Finally, V would like to remind, in the actual banking system, of course, also need to consider security, transactional, persistence, and error handling and other factors, RMI network communications also need to be carried out in a secure network environment, in order to prevent data leakage or tampering. How do you use RMI in your application, welcome to pay attention to Wei brother love programming, together with the exchange of ha.