我在很多地方搜索过解决方案,但没有找到。
我的问题是如何定义一个离线方法,所以当我从RMI服务器获取对象后, 我将能够调用此方法,它不会从服务器获取数据,而是从客户端中的对象获取数据。
更具体地说,我有一个包含 2 个方法和一个私有(private)变量的数据库类。 方法1:返回变量的值(属性方法..) - 应该是离线方法,因为我已经在客户端对象中拥有该变量。 方法2:向数据库插入新数据(sql命令..)。 - 应该是在线方法,以便服务器可以连接到数据库。
非常感谢!
最佳答案
你不能这么做。您将需要调整您的设计。令人高兴的是,我认为您不需要对设计进行太多调整。
关键是能够确定每个对象是远程对象还是本地对象。对远程对象的调用将转到服务器,而对本地对象的调用将保留在本地。如果您想同时拥有一个对象,则需要将其一分为二,这样您就拥有了本地部分和远程部分。为了为客户端维护一个方便的界面,您可以将远程对象隐藏在本地对象后面。
以下是如何执行此操作的草图:
public interface RemoteDatabase extends Remote {
public void insertData(String data) throws RemoteException;
}
public class RemoteDatabaseImpl implements RemoteDatabase {
@Override
public void insertData(String data) throws RemoteException {
// whatever
}
}
public class Database implements Serializable {
private final RemoteDatabase remote;
private final String property;
public Database(RemoteDatabase remote, String property) {
this.remote = remote;
this.property = property;
}
public String getProperty() {
return property;
}
public void insertData(String data) throws RemoteException {
remote.insertData(data);
}
}
请注意,当您在服务器上创建 Database
实例时,您需要为其指定 stub用于 RemoteDatabaseImpl
实现,而不是真实的东西(我认为)。
您甚至可以让它们实现相同的接口(interface),以加强对象之间的关系。像这样的事情:
public interface RemoteDatabase extends Remote {
public String getProperty() throws RemoteException;
public void insertData(String data) throws RemoteException;
}
public class RemoteDatabaseImpl implements RemoteDatabase {
@Override
public void insertData(String data) throws RemoteException {
// whatever
}
@Override
public String getProperty() {
return "whatever";
}
public Database toLocal() throws NoSuchObjectException {
return new Database((RemoteDatabase) PortableRemoteObject.toStub(this), getProperty());
}
}
public class Database implements RemoteDatabase, Serializable {
private final RemoteDatabase remote;
private final String property;
public Database(RemoteDatabase remote, String property) {
this.remote = remote;
this.property = property;
}
@Override
public String getProperty() {
return property;
}
@Override
public void insertData(String data) throws RemoteException {
remote.insertData(data);
}
}
关于JAVA RMI,定义离线方法,所以当方法调用时不会去服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13702441/