gpt4 book ai didi

java - 如何在 RMI 方法的参数中传递对象?

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:14:00 27 4
gpt4 key购买 nike

我正在尝试在 RMI 方法中添加参数。当我添加例如String 一切正常。但是我不确定我是否可以传递我创建的对象。我是 RMI 新手,所以我的代码非常简单:

你好

public interface HelloIF extends Remote {
String greeting(Context c) throws RemoteException;
}

你好

public class Hello extends UnicastRemoteObject implements HelloIF {

public Hello() throws RemoteException {
}

public String greeting(Context c) throws RemoteException {
addToContext(c);
report(c);
return "greeting";
}

void addToContext(Context c) {
c.addID(Thread.currentThread().getId());
}

void report(Context c) {
System.out.println("Hello.greeting() thread : "
+ Thread.currentThread().getName() + " "
+ Thread.currentThread().getId());

System.out.println("Hello.greeting() context : "
+ c.getDistributedThreadName() + " " + c.getRequestType());
}
}

RMI服务器

public class RMIServer {

public static void main(String[] args) throws RemoteException, MalformedURLException {
LocateRegistry.createRegistry(1099);
HelloIF hello = new Hello();
Naming.rebind("server.Hello", hello);
System.out.println("server.RMI Server is ready.");
System.out.println("RMIServer.main() thread : " + Thread.currentThread().getName()
+ " " + Thread.currentThread().getId());
}
}

RMI客户端

public class RMIClient {
public static void main(String[] args) throws RemoteException, MalformedURLException, NotBoundException {

Context context = new Context("request1", Thread.currentThread().getName()+System.currentTimeMillis());

Registry registry = LocateRegistry.getRegistry("localhost");
HelloIF hello = (HelloIF) registry.lookup("server.Hello");
System.out.println(hello.greeting(context));
System.out.println("RMIClient.mian() thread : " + Thread.currentThread().getName()
+ " " + Thread.currentThread().getId());
}
}

最后是我的类(class)背景

public class Context 
{
private String requestType;
private String distributedThreadName;
private List<Long> IDList;

(...) getters/setters
}

我应该怎么做才能使传递 Context 成为可能?

最佳答案

您的对象应该实现Serializable。如我所见,这将是一个问题。这是必需的,因为两个部分之间的通信是使用序列化完成的,因此需要发送到另一部分的每个对象都需要是实现 Serializable 的类的实例。

public class Context implements Serializable
{
private String requestType;
private String distributedThreadName;
private List<Long> IDList;

(...) getters/setters
}

请添加一个 serialVersionUID 作为一个好的习惯。像这样的东西:

private static final long serialVersionUID = 20120731125400L;

关于java - 如何在 RMI 方法的参数中传递对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11736347/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com