Java通過Hadoop實現RPC通訊簡單例項
阿新 • • 發佈:2018-12-18
一、定義server端程式碼
1.定義一個介面,該介面繼承org.apache.hadoop.ipc.VersionedProtocol介面
import org.apache.hadoop.ipc.VersionedProtocol; /** * 1.伺服器定義介面 */ public interface HelloServer extends VersionedProtocol { //版本號--用於通訊暗號 long versionID= 123L; String sayHello(String name); }
2.定義實現以上介面的實現類
import org.apache.hadoop.ipc.ProtocolSignature; import java.io.IOException; /** * 2.定義介面實現類 */ public class HelloServiceImpl implements HelloServer { public String sayHello(String name) { return "hello: "+name; } public long getProtocolVersion(String s, long l) throws IOException { return versionID; } public ProtocolSignature getProtocolSignature(String s, long l, int i) throws IOException { return null; } }
3.測試開啟一個服務端:用於暴露埠
import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.ipc.RPC; import java.io.IOException; /** * 暴露介面 */ public class HelloService { public static void main(String[] args) throws IOException { HelloServiceImpl instance = new HelloServiceImpl(); // 建立一個RPC builder RPC.Builder builder = new RPC.Builder(new Configuration()); //指定RPC Server的引數 builder.setBindAddress("localhost"); builder.setPort(7788); //將自己的程式部署到server上 builder.setProtocol(HelloServer.class); builder.setInstance(instance); //建立Server RPC.Server server = builder.build(); //啟動服務 server.start(); System.out.println("server is start"); } }
二、客戶端程式碼
import java.io.IOException; import java.net.InetSocketAddress; public class HelloClient { public static void main(String[] args) throws IOException { /** * HelloServer:服務端介面類 * 123L:通訊發暗號 * InetSocketAddress:服務端地址 * Configuration: */ HelloServer proxy = RPC.getProxy(HelloServer.class, 123L, new InetSocketAddress("localhost", 7788), new Configuration()); String result = proxy.sayHello("tom"); System.out.println("結果是: "+result); } }
三、測試
首先開啟服務端--HelloService
開啟客戶端-提交任務--HelloClient