前段时间,公司做web service的时候,看了一下资料,当时看见一个叫rmi的东西(远程方法调用),最近闲着,所以看了一下 ,感觉挺简单的!所以写了一个例子提供给大家把!
rmi的服务端,必须要使用接口,同时还有接口的实现类!所以下面的两个文件是接口类和接口的实现类!
UserDao 接口:
-
-
-
-
-
-
-
- public interface UserDao extends Remote{
-
-
-
-
- public void sayName(String name) throws RemoteException;
- }
|
UserDaoImpl实现类
-
-
-
-
-
-
-
-
- public class UserDaoImpl extends UnicastRemoteObject implements UserDao {
- public UserDaoImpl() throws RemoteException {
- }
- @Override
- public void sayName(String name) {
- if(name!=null&&!name.equals(""))
- {
- System.out.println("我的名字是:"+name);
- }else{
- System.err.println("名字不为空....");
- }
- }
- }
|
对外的提供一个服务,服务中已经共享了url给外界访问
-
-
-
-
-
-
-
- public class StartService {
- private static final String IP = "127.0.0.1";
- private static final int PORT = 9999;
- private static final String REMOTE_NAME = "userDao";
- private static final String REMOTE_URL = "rmi://"+IP+":"+PORT+"/"+REMOTE_NAME;
- public static void main(String[] args) {
- try {
- UserDao userDao = new UserDaoImpl();
- LocateRegistry.createRegistry(PORT);
- Naming.bind(REMOTE_URL, userDao);
- System.out.println("远程"+REMOTE_NAME+"启动成功....");
- } catch (RemoteException e) {
- System.err.println("远程对象出错");
- e.printStackTrace();
- } catch (MalformedURLException e) {
- System.err.println("URL出错了");
- e.printStackTrace();
- } catch (AlreadyBoundException e) {
- System.err.println("绑定的对象已经存在了");
- e.printStackTrace();
- }
- }
- }
|