欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

基于java.rmi的RPC远程方法调用

程序员文章站 2022-07-11 18:03:35
...

服务提供者

开启本地服务及注册

package com.jxl.rmi;

import java.rmi.AlreadyBoundException;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;

/**
 * @Auther: 
 * @Date: 2020/8/14 - 08 - 14 - 17:23
 * @Description: com.jxl.rmi
 * @version: 1.0
 */
public class ServiceMain {

    public static void main(String[] args) throws Exception {
        //实例化 要暴露的本地方法或接口
        ISayService sayService = new SayServiceImpl();
        //开启本地服务
        ISayService iSayService = (ISayService)UnicastRemoteObject.exportObject(sayService, 666);
        //服务注册中心
        Registry registry = LocateRegistry.createRegistry(999);
        //注册服务
        registry.bind("sayService",iSayService);

    }
}

服务接口

package com.jxl.rmi;

import java.rmi.Remote;

/**
 * @Auther: 
 * @Date: 2020/8/14 - 08 - 14 - 17:20
 * @Description: com.jxl.rmi
 * @version: 1.0
 */
public interface ISayService extends Remote {

    public String sayHi(String name) throws Exception;
}

接口实现

package com.jxl.rmi;

/**
 * @Auther: 
 * @Date: 2020/8/14 - 08 - 14 - 17:13
 * @Description: com.jxl.rmi
 * @version: 1.0
 */
public class SayServiceImpl implements ISayService {

    public String sayHi(String name){
        System.out.println(name);
        return name+" 你好!";
    }
}

消费方像调用远程方法一样调用本地方法

需把调用服务方的接口放到当前项目中

package com.jxl.rmi;

import java.rmi.Remote;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

/**
 * @Auther: 
 * @Date: 2020/8/14 - 08 - 14 - 17:39
 * @Description: com.jxl.rmi
 * @version: 1.0
 */
public class CosumenterMain {

    public static void main(String[] args) throws Exception {
        Registry registry = LocateRegistry.getRegistry(999);
        ISayService iSayService = (ISayService)registry.lookup("sayService");
        String str = iSayService.sayHi("张三");
        System.out.println(str);
    }
}