java Remote调用远程方法及服务端接口定义

1.Remote调用远程

/*

* Remote调用远程服务

*/

public class MyRemoteClient {
    public void go(){
        try {
            //lookup 返回与指定 name 关联的远程对象的引用
            //bind(String name, Remote obj) 指定 name 绑定到远程对象。
            MyRemote service = 
                     (MyRemote)Naming.lookup("rmi://127.0.0.1/MyRemote/RemoteHello");
            String s = service.sayHello(2020);
            System.out.println(s);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args){        
        new MyRemoteClient().go();
    }
}

2.Java接口定义

/**
 * RMI 提供一些远程对象实现可以扩展的有用类,这些类便于远程对象创建。
 * Remote 接口用于标识其方法可以从非本地虚拟机上调用的接口。任何远程对象都必须直接或间接实现此
 * 接口。只有在“远程接口”中指定的这些方法才可远程使用。
*/
import java.rmi.Remote;

import java.rmi.RemoteException;

public interface MyRemote extends Remote{
    //定义接口
    public String sayHello(int year) throws RemoteException;
}

3.接口实现

import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import com.XXX.RemoteInterface.MyRemote;

/*
*远程服务实现
*/
@SuppressWarnings("serial")
public class MyRemoteImpl extends UnicastRemoteObject implements MyRemote{
    public String sayHello(int year) throws RemoteException {
        return "I invoking this Method names sayHello() in "+year;
    }

    //此处为空的构造方法
    public MyRemoteImpl() throws RemoteException {}

    public static void main(String[] args){
        try {
            MyRemote service = new MyRemoteImpl();
            //将指定名称重新绑定到一个新的远程对象。
            Naming.rebind("/MyRemote/RemoteHello", service);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值