大体分四部分:客户端---RMI注册表---服务器---Web服务器
一、客户端:
import java.rmi.*;
public interface Warehouse extends Remote
{
double getPrice(String description) throws RemoteException;
}
二、服务器端:
import java.rmi.*;
import java.rmi.server.*;
import javar.util.*;
public class WarehouseImpl extends UnicastRemoteObject implements Warehouse
{
public WarehouseImple() throws RemoteException
{
prices = new HashMap<String, Double>();
prices.put("BLL",23.2);
prices.put("LLL",24.1);
}
public double getPrice(String description) throws RemoteException
{
Double price = prices.get(description);
return price==null?0:price;
}
private Map<String, Double> prices;
}
三、RMI注册
import java.rmi.*;
import javax.naming.*;
public class WarehouseServer
{
public static void main(String[] args) throws RemoteException, NamingException
{
WarehouseImpl central = new WarehouseImpl();
Context namingContext = new InitialContext();
namingContext.bind("rmi:central_warehouse", central);
}
}
四、客户端调用
import java.rmi.*;
import java.util.*;
import javax.naming.*;
public class WarehouseClient
{
public static void main(String[] args)throws NamingExcepion, RemoteException
{
Context namingContext = new InitialContext();
String uri="rmi://localhost/central_warehouse";
Warehouse central = (Warehouse) namingContext.lookup(uri);
String description ="LLL";
double price=central.getPrice(description);
System.out.println(description+"="+price);
}
}