赞
踩
RPC的使用
代码如下:
LoginServiceInterface.java
- package rpc;
-
- public interface LoginServiceInterface
- {
- public static final long versionID=1L;
- public String login(String userName,String pwd);
- }
注意该接口versionID版本号必须设置,否则客户端调用时报错
- Exception in thread "main" java.lang.RuntimeException: java.lang.NoSuchFieldException: versionID
- at org.apache.hadoop.ipc.RPC.getProtocolVersion(RPC.java:179)
- at org.apache.hadoop.ipc.WritableRpcEngine$Invocation.<init>(WritableRpcEngine.java:113)
- at org.apache.hadoop.ipc.WritableRpcEngine$Invoker.invoke(WritableRpcEngine.java:252)
- at com.sun.proxy.$Proxy4.login(Unknown Source)
- at rpc.LoginController.main(LoginController.java:18)
- Caused by: java.lang.NoSuchFieldException: versionID
- at java.lang.Class.getField(Class.java:1703)
- at org.apache.hadoop.ipc.RPC.getProtocolVersion(RPC.java:175)
- ... 4 more
LoginServiceImpl.java
- package rpc;
-
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
-
- public class LoginServiceImpl implements LoginServiceInterface
- {
- private static final Logger logger = LoggerFactory.getLogger(LoginServiceImpl.class);
-
- @Override
- public String login(String userName, String pwd)
- {
- return userName + " logged in successfully!";
- }
- }
服务端启动 Starter.java
- package rpc;
-
- import org.apache.hadoop.conf.Configuration;
- import org.apache.hadoop.ipc.RPC;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
-
- import java.io.IOException;
-
- public class Starter
- {
- private static final Logger logger = LoggerFactory.getLogger(Starter.class);
-
- public static void main(String[] args) throws IOException
- {
- RPC.Builder builder = new RPC.Builder(new Configuration());
- builder.setBindAddress("192.168.1.103").setPort(10000).setProtocol(LoginServiceInterface.class).setInstance(new LoginServiceImpl());
- RPC.Server server = builder.build();
- server.start();
- }
- }
客户端启动LoginController.java
- package rpc;
-
- import org.apache.hadoop.conf.Configuration;
- import org.apache.hadoop.ipc.RPC;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
-
- import java.io.IOException;
- import java.net.InetSocketAddress;
-
- public class LoginController
- {
- private static final Logger logger = LoggerFactory.getLogger(LoginController.class);
-
- public static void main(String[] args) throws IOException
- {
- LoginServiceInterface loginServiceInterface = RPC.getProxy(LoginServiceInterface.class, 1L, new InetSocketAddress("192.168.1.103",10000), new Configuration());
- String result = loginServiceInterface.login("xuliang", "123");
- logger.debug("result: " + result);
- }
- }
客户端运行结果:
欢迎大家私信博主,邀你进技术交流群
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。