腾讯云上部署RMI

看《Head First Design Pattern》的代理模式,先叙述了一个远程代理,用到RMI。

书上的实例是本地部署的,尝试一下在服务器部署RMI。

腾讯云配置:

1核 2GB 1Mbps

系统盘:普通云硬盘

网络:Default-VPC

公网IP:193.112.16.223


目录结构

云端:



客户端:



代码:

云端:

修改GumballMachineTestDrive.java,如下

package proxy.remoteproxy;

import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.RemoteException;

public class GumballMachineTestDrive {
	
	public static void main(String[] args) {
		int count = 0;
		GumballMachineRemote gumballMachine = null;
		
		if (args.length < 2) {
			System.out.println("GumballMachine <name> <inventory>");
			System.exit(1);
		}
		
		count = Integer.parseInt(args[1]);
		
		try {
			System.setProperty("java.rmi.server.hostname", "193.112.16.223");
			
			gumballMachine = new GumballMachine(args[0], count);
			Naming.rebind(args[0], gumballMachine);
			System.out.println(" rmi server is ready...");
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}



客户端:

修改GumballMonitorTestDrive.java,如下

package proxy.remoteproxy;

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

public class GumballMonitorTestDrive {
	public static void main(String[] args) {
		String[] location = {
				"rmi://193.112.16.223/santafe",
				"rmi://193.112.16.223/boulder",
				"rmi://193.112.16.223/seattle"
		};
		
		GumballMonitor[] monitor = new GumballMonitor[location.length];
		
		for (int i = 0; i < location.length; i++) {
			try {
				GumballMachineRemote machine = (GumballMachineRemote) Naming.lookup(location[i]);
				monitor[i] = new GumballMonitor(machine);
				System.out.println(monitor[i]);
			} catch (RemoteException | MalformedURLException | NotBoundException e) {
				e.printStackTrace();
			}
		}
		
		for (int i = 0; i < monitor.length; i++) {
			monitor[i].report();
		}
	}
}

运行:

1. 云端启动

rmiregistry
java proxy.remoteproxy.GumballMachineTestDrive seattle 350
java proxy.remoteproxy.GumballMachineTestDrive santaft 100
java proxy.remoteproxy.GumballMachineTestDrive boulder 300

2. 客户端启动


结果如图所示,才从客户端获取到云端的信息。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值