最近当涉及到spring rmi操作时,对于客户端提供接口给服务器端的情况还是第一次使用,今天晚上抽出一点时间做了一个小程序,希望能给spring rmi应用者,带来帮助,同时希望大家互相讨论.
1.程序分为客户端和服务端,分别用clientRmi,serverRmi来表示
1.1客户端三个类.
(1).IMessage(接口)
package client;
import java.util.List;
public interface IMessage {
public void putMessage(String str);
public List<String> getMessage();
}
(2).MessageImpl(上边接口的实现类)
package client;
import java.util.ArrayList;
import java.util.List;
public class MessageImpl implements IMessage {
private static List<String> strings = new ArrayList<String>();
@Override
public List<String> getMessage() {
synchronized (strings) {
while (true) {
if (strings.size() == 0) {
try {
strings.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
return strings;
}
}
}
}
@Override
public void putMessage(String str) {
synchronized (strings) {
strings.add(str);
strings.notifyAll();
}
}
}
(3).MainClient(包含Main方法)
package client;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainClient {
public static void main(String[] args) {
ApplicationContext factory = new ClassPathXmlApplicationContext(
"clientRmi.xml");
final IMessage mess = (IMessage) factory.getBean("messageImpl");
Runnable run = new Runnable() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(mess.getMessage().size());
}
}
};
Thread thread = new Thread(run);
thread.start();
}
}
2.2服务器端也有三个类
(1).IMessage(接口和上边的一样)
(2).ThreadTool(线程工具类)这个类通过rmi访问client端的messageImpl类并且传递值过去
package server;
public class ThreadTool implements Runnable {
private IMessage message;
public void setMessage(IMessage message) {
this.message = message;
}
@Override
public void run() {
for (int i = 0; i < 100000; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
message.putMessage("value" + i);
}
}
}
(3).MainServer(启动server端的类)
package server;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainServer {
public static void main(String[] args) {
ApplicationContext factory = new ClassPathXmlApplicationContext(
"serverRmi.xml");
ThreadTool threadTool = (ThreadTool) factory.getBean("threadTool");
threadTool.run();
}
}
首先启动client端,然后是server端,打开client端的控制台,server端将定时想client的List<String>数据结构中放入值.client的Console中便可以看到结果.