Java RMI 使用例子

Posted junge8619

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java RMI 使用例子相关的知识,希望对你有一定的参考价值。

1.创建协议接口(UserService)

/**
 * 
 */
package com.junge.demo.rmi.protocol.service;

import java.io.Serializable;
import java.rmi.Remote;
import java.rmi.RemoteException;

import com.junge.demo.rmi.protocol.model.User;

/**
 * @author Administrator
 *
 */
public interface UserService extends Remote, Serializable {

    Integer addUser(User user) throws RemoteException;
    
    void delUser(Integer userid) throws RemoteException;
    
    void modifyUser(User user) throws RemoteException;
    
    User getUserByUserId(Integer userid) throws RemoteException;
}

User.java

/**
 * 
 */
package com.junge.demo.rmi.protocol.model;

import java.io.Serializable;

/**
 * @author Administrator
 *
 */
public class User implements Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = -8967262939434460765L;

    private Integer userid;
    private String username;

    public Integer getUserid() {
        return userid;
    }

    public void setUserid(Integer userid) {
        this.userid = userid;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    @Override
    public String toString() {
        return "User [userid=" + userid + ", username=" + username + "]";
    }
}

2、创建服务实现类UserServiceProvider.java

package com.junge.demo.rmi.server.service.provider;

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

import com.junge.demo.rmi.protocol.model.User;
import com.junge.demo.rmi.protocol.service.UserService;

public class UserServiceProvider extends UnicastRemoteObject implements UserService {
    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    
    public UserServiceProvider() throws RemoteException {
        super();
    }

    public Integer addUser(User user) throws RemoteException {
        System.out.println("addUser:" + user);
        return user.getUserid();
    }

    public void delUser(Integer userid) throws RemoteException {
        System.out.println("delUser,userid=" + userid);
        
    }

    public void modifyUser(User user) throws RemoteException {
        System.out.println("modifyUser:" + user);
        
    }

    public User getUserByUserId(Integer userid) throws RemoteException {
        System.out.println("getUserByUserId,userid={}" + userid);
        
        User user = new User();
        user.setUserid(userid);
        user.setUsername("寮犱笁");
        return user;
    }
}

3.启动注册表,注册服务(ServiceStartServlet.java)

/**
 * 
 */
package com.junge.demo.rmi.server.service.start;

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

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

import com.alibaba.fastjson.JSONObject;
import com.junge.demo.rmi.server.service.provider.UserServiceProvider;

/**
 * @author Administrator
 *
 */
public class ServiceStartServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;
    
    private Registry registry;
    
    private static final String BIND_NAME = "com.junge.demo.rmi.protocol.service.UserService";
    
    private Registry getRegistry() throws RemoteException {
        return LocateRegistry.createRegistry(1099);
    }

    @Override
    public void init() throws ServletException {
        
        try {
            registry = getRegistry();
            System.out.println(JSONObject.toJSON(registry.list()));
            registry.rebind(BIND_NAME, new UserServiceProvider());
            
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }
    
    @Override
    public void destroy() {
        if (null != registry) {
            try {
                registry.unbind(BIND_NAME);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}

4.创建客户端调用rmi(RmiClient.java)

/**
 * 
 */
package com.junge.demo.rmi;

import java.rmi.Naming;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import com.junge.demo.rmi.protocol.model.User;
import com.junge.demo.rmi.protocol.service.UserService;

/**
 * @author Administrator
 *
 */
public class RmiClient {

    /**
     * @param args
     */
    public static void main(String[] args) {
        addUserBatch();

    }
    
    public static void addUserBatch() {

        Long btime = System.currentTimeMillis();

        
        ThreadPoolExecutor executor = new ThreadPoolExecutor(10, 1000, 200L, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(50000));

        try {
            UserService userService = (UserService)Naming.lookup("com.junge.demo.rmi.protocol.service.UserService");
            for (int i = 0; i < 50000; i++) {
                executor.submit(new OperUser(userService));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            executor.shutdown();
        }
        
        Long etime = System.currentTimeMillis();

        System.out.println(etime - btime);
    }

}

class OperUser implements Runnable {
    private UserService userService;

    public OperUser(UserService userService) {
        this.userService = userService;
    }

    @Override
    public void run() {
        try {
            // 增加、详情、修改、删除
            User user = new User();
            user.setUserid(1);
            user.setUsername("名字");
            userService.addUser(user);

            User user2 = userService.getUserByUserId(1);

            userService.modifyUser(user2);

            userService.delUser(user2.getUserid());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

 

5.注意实现

a.协议接口需要继承Remote接口,对外提供的接口需要抛出RemoteException异常

b.协议接口中使用的对象需要实现序列化接口Serializable

c.服务端实现类需要继承UnicastRemoteObject类

6.问题

1.使用maven工程创建的服务端,直接使用java application运行服务端,找不到协议接口

以上是关于Java RMI 使用例子的主要内容,如果未能解决你的问题,请参考以下文章

请问java RMI的意义? [关闭]

java rmi 小记

使用 java RMI 和 CORBA 的分布式计算

RMI 客户端显示 java.rmi.NotBoundException 错误

Java 中 RMI 的使用

RMI是干啥用的在JAVA里面