java实现简单的RPC服务调用

作者: adm 分类: java 发布时间: 2022-10-30

基础准备:

//UserEntity
import java.io.Serializable;
public class UserEntity implements Serializable {
    private Integer id;
    private String name;
    private String sex;
  // Getter and Setter方法
}
//IUserService
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.util.List;
public interface IUserService extends Remote {
    List query() throws RemoteException;
    Integer create(UserEntity userEntity) throws RemoteException;
}

将包含IUserService和UserEntity的工程打包成jar,在rpc客户端工程和prc服务端的工程中引入jar包

1 rpc服务端代码如下: Main方法运行后对外提供prc服务

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.ArrayList;
import java.util.List;
public class UserService extends UnicastRemoteObject implements IUserService {
    protected UserService() throws RemoteException {
    }

    @Override
    public List query() throws RemoteException {
        List userEntityList = new ArrayList<>();
        UserEntity userEntity = new UserEntity();
        userEntity.setId(1);
        userEntity.setName("张三");
        userEntity.setSex("男");
        userEntityList.add(userEntity);
        return userEntityList;
    }

    @Override
    public Integer create(UserEntity userEntity) throws RemoteException {
        System.out.println("用户姓名为:" + userEntity.getName());
        return 8;
    }
}
import java.rmi.AlreadyBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

public class Main {
    public static void main(String[] args) throws RemoteException, AlreadyBoundException {
        Registry registry= LocateRegistry.createRegistry(9090);
        UserService userService=new UserService();
        registry.bind("user",userService);
    }
}

–下面是rpc客户端实现

//interface IUserService
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.util.List;

public interface IUserService extends Remote {
    List query() throws RemoteException;
    Integer create(UserEntity userEntity) throws RemoteException;
}

Main方法


import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.util.List;

public class Main {
    public static void main(String[] args) throws RemoteException, NotBoundException, MalformedURLException {
        String url = "rmi://localhost:9090/user";
        IUserService userService = (IUserService) Naming.lookup(url);
        List entityList = userService.query();
        System.out.println(entityList);
        UserEntity userEntity=new UserEntity();
        userEntity.setName("杰斯");
        userEntity.setId(2);
        userEntity.setSex("女");

        Integer integer = userService.create(userEntity);
        System.out.println(integer);
    }
}

如果觉得我的文章对您有用,请随意赞赏。您的支持将鼓励我继续创作!