小言_互联网的博客

大型网站技术和java中间件 - 补:RMI(Remote Method Invoation) java本地调用

373人阅读  评论(0)

大型网站技术和java中间件 - 补:RMI(Remote Method Invoation) java本地调用

//客户端必须要依赖
//接口及接口依赖的相关class


I.远程接口

/**

* 远程调用的接口 -> 客户端必须要依赖的

*/

interface RMIIUser extends Remote {

    //必需要抛出RemoteException
    String getUserName(int id) throws RemoteException;

    int getUserCount() throws RemoteException;

    User getUserByName(String name) throws RemoteException;

}



II.依赖的相关class

/**

* 传输的对象,客户端也必须要依赖

*/

class User implements Serializable {

    // 该字段必须存在 -> 为了序列化成功

    private static final long serialVersionUID = 42L;

    String name;

    int id;

    public User(String name, int id) {

        this.name = name;

        this.id = id;

    }

}

 

 

//只需要在server端存在的


I.接口的实现

/**

* 接口的实现 -> 作为server存在就行

*/

@Slf4j

class RMIIUserImpl extends UnicastRemoteObject implements RMIIUser {

    // 该构造期必须存在,因为集继承了UnicastRemoteObject类,其构造器要抛出RemoteException

    public RMIIUserImpl() throws RemoteException {

        super();

    }


    @Override

    public String getUserName(int id) throws RemoteException {

        log.info("{}{}", getClass(), "正在远程调用");

        return "lmy86263";

    }


    @Override

    public int getUserCount() throws RemoteException {

        return 1;

    }


    @Override

    public User getUserByName(String name) throws RemoteException {

        return new User("lmy86263", 1);

    }

}



II.绑定的逻辑

/**

* 注册RMI

*/

public class RemoteModel {



    public static void main(String[] args) {

        RMIIUser rmiiUser = null;

        Registry registry = null;

        try {

            registry = LocateRegistry.createRegistry(1099);

            rmiiUser = new RMIIUserImpl();

            registry.rebind("demo.spring.boot.demospringboot.remote.RMIIUser", rmiiUser);

            System.out.println(" rmi server is ready ...");

        } catch (Exception e) {

            e.printStackTrace();

        }

    }

}

 

//客户端调用程序


import java.net.MalformedURLException;

import java.rmi.Naming;

import java.rmi.NotBoundException;

import java.rmi.RemoteException;



public class Client {

    public static void main(String[] args) {

        try {

            String url  = "rmi://localhost:1099/demo.spring.boot.demospringboot.remote.RMIIUser";

            RMIIUser handler = (RMIIUser) Naming.lookup(url);

            int count = handler.getUserCount();

            String name = handler.getUserName(1);

            System.out.println("name: " + name);

            System.out.println("count: " + count);

            System.out.println("user: " + handler.getUserByName("lmy86263"));

        } catch (NotBoundException e) {

            e.printStackTrace();

        } catch (MalformedURLException e) {

            e.printStackTrace();

        } catch (RemoteException e) {

            e.printStackTrace();

        }

    }

}

 


转载:https://blog.csdn.net/one_chao/article/details/101983281
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场