公司做web service的時候,看了一下資料,當時看見一個叫rmi的東西(遠程方法調用),最近閑著,所以看了一下 ,感覺挺簡單的!所以寫了一個例子提供給大家把!
rmi的服務端,必須要使用接口,同時還有接口的實現類!所以下面的兩個文件是接口類和接口的實現類!
UserDao 接口:
-
-
-
-
-
-
-
- public interface UserDao extends Remote{
-
-
-
-
- public void sayName(String name) throws RemoteException;
-
-
- }
UserDaoImpl實現類
-
-
-
-
-
-
-
-
- public class UserDaoImpl extends UnicastRemoteObject implements UserDao {
-
- public UserDaoImpl() throws RemoteException {
- }
- @Override
- public void sayName(String name) {
- if(name!=null&&!name.equals(""))
- {
- System.out.println("我的名字是:"+name);
- }else{
- System.err.println("名字不為空....");
- }
- }
-
- }
對外的提供一個服務,服務中已經共享了url給外界訪問
-
-
-
-
-
-
-
- public class StartService {
- private static final String IP = "127.0.0.1";
- private static final int PORT = 9999;
- private static final String REMOTE_NAME = "userDao";
- private static final String REMOTE_URL = "rmi://"+IP+":"+PORT+"/"+REMOTE_NAME;
- public static void main(String[] args) {
- try {
- UserDao userDao = new UserDaoImpl();
- LocateRegistry.createRegistry(PORT);
- Naming.bind(REMOTE_URL, userDao);
- System.out.println("遠程"+REMOTE_NAME+"啟動成功....");
- } catch (RemoteException e) {
- System.err.println("遠程對象出錯");
- e.printStackTrace();
- } catch (MalformedURLException e) {
- System.err.println("URL出錯了");
- e.printStackTrace();
- } catch (AlreadyBoundException e) {
- System.err.println("綁定的對象已經存在了");
- e.printStackTrace();
- }
- }
- }
上面是服務端的代碼,如果啟動沒有任何問題,就可以做客戶端訪問了,其實上海旋塞閥客戶端的訪問更加的簡單,只需要遠程的接口類和查詢rmi中的url就可以了!
代碼如下:
-
-
-
-
-
-
-
-
- public class TestRemote {
- public static void main(String[] args) {
- try {
-
- UserDao userDao = (UserDao) Naming.lookup("rmi://127.0.0.1:9999/userDao");
-
- userDao.sayName("spring sky");
- } catch (MalformedURLException e) {
- System.err.println("URL出錯");
- e.printStackTrace();
- } catch (RemoteException e) {
- System.err.println("遠程對象出錯");
- e.printStackTrace();
- } catch (NotBoundException e) {
- System.err.println("沒有找到綁定的對象");
- e.printStackTrace();
- }
- }
- }
以上就是所有的rmi遠程調用代碼了!運行結果如下:

好了,本人也只是簡單的了解了rmi,如果以后有項目做rmi就可以深入了! 呵呵 ,在這里我突然感覺,想web service也應該和他一樣的原理的把!