1. 程式人生 > >Java RMI 使用例子

Java RMI 使用例子

pack let add return 使用 lib 繼承 json.js maven工程

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 使用例子