服务提供者

服务接口:

public interface HelloService {
public String sayHello(String name);
}

服务实现类:

public class HelloServiceImpl implements HelloService {
@Override
public String sayHello(String name) {
return "hello:" + name;
}
}

服务注册:

public class ProviderReflect {
private static final ThreadPoolExecutor executor = new ThreadPoolExecutor(2, 5, 1, TimeUnit.MINUTES, new LinkedBlockingDeque<Runnable>(1000), new MyThreadFactory("providerReflact")); /**
* 服务发布
*
* @param service
* @param port
*/
public static void provider(final Object service, int port) {
ServerSocket serverSocket = null; try {
serverSocket = new ServerSocket(port);
while (true) {
Socket socket = serverSocket.accept();
executor.execute(new Runnable() {
@Override
public void run() {
ObjectOutputStream oos = null;
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(socket.getInputStream()); // 请求调用的方法名
String methodName = ois.readUTF();
// 请求的参数
Object[] args = (Object[]) ois.readObject(); oos = new ObjectOutputStream(socket.getOutputStream());
Object result = MethodUtils.invokeExactMethod(service, methodName, args);
System.out.println(result);
// 写结果
oos.writeObject(result);
} catch (IOException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
if (oos != null) {
try {
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (ois != null) {
try {
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
});
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
} }
} static class MyThreadFactory implements ThreadFactory {
/**
* 线程池中的线程名称前缀
*/
private String namePrefix; /**
* 原子的整型
*/
private AtomicInteger atomicInteger = new AtomicInteger(1); public MyThreadFactory(String whatFeaturOfGroup) {
this.namePrefix = "From MyThreadFactory:" + whatFeaturOfGroup + "-worker-";
} @Override
public Thread newThread(Runnable r) {
String name = namePrefix + atomicInteger.getAndIncrement();
Thread thread = new Thread(r, name);
System.out.println(thread.getName());
return thread;
}
} /**
* 发布服务
*
* @param args
*/
public static void main(String[] args) {
HelloService helloService = new HelloServiceImpl();
ProviderReflect.provider(helloService, 8082);
}
}

pom.xml:

       <dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.4</version>
</dependency>

服务消费者

消费接口:

public interface HelloService {
public String sayHello(String name);
}

接口的代理:

public class ConsumerProxy {
public static <T> T consume(final Class<?> serviceClass, final String host, final int port) {
return (T) Proxy.newProxyInstance(serviceClass.getClassLoader(), new Class<?>[]{serviceClass}, new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Socket socket = null;
ObjectOutputStream output = null;
ObjectInputStream input = null;
try {
socket = new Socket(host, port);
output = new ObjectOutputStream(socket.getOutputStream());
// output.writeUTF(serviceClass.getName());
output.writeUTF(method.getName());
// output.writeObject(method.getParameterTypes());
output.writeObject(args);
input = new ObjectInputStream(socket.getInputStream());
return input.readObject();
} finally {
if (socket != null) {
socket.close();
}
if (output != null) {
output.close();
}
if (input != null) {
input.close();
}
}
}
});
} public static void main(String[] args) {
HelloService helloService = ConsumerProxy.consume(HelloService.class, "127.0.0.1", 8082);
String response = helloService.sayHello("yangyongjie");
System.out.println(response);
}
}

输出:

hello:yangyongjie

自实现RPC调用的更多相关文章

  1. 闲话RPC调用

    原创文章转载请注明出处:@协思, http://zeeman.cnblogs.com 自SOA架构理念提出以来,应用程序间如何以最低耦合度通信的问题便呈现在所有架构师面前. 互联网系统的复杂度让我们不 ...

  2. RabbitMQ学习笔记5-简单的RPC调用

    利用空的queue名字("")让rabbitMQ生成一个唯一的队列名称,同时指定队列是:临时的(auto-delete).私有的(exclusive). 在发送的RPC调用消息里设 ...

  3. Hadoop学习记录(3)|HDFS API 操作|RPC调用

    HDFS的API操作 URL方式访问 package hdfs; import java.io.IOException; import java.io.InputStream; import java ...

  4. 使用RPC 调用NameNode中的方法

    用户在Client 端是很难对 NameNode中的信息进行直接访问的, 所以 ,在Hadoop系统中为 Client端 提供了一系列的方法调用,这些方法调用是通过RPC 方法来实现的, 根据RPC ...

  5. Unity3D RPC调用顺序问题

    使用Unity自带的Network实现多人协同任务时,因为使用RPC传递消息.RPC即远程过程调用,对于它的使用,第一反应的问题就是如果连续两次调用RPC,RPC的函数会顺序执行吗?还是只要RPC的消 ...

  6. 给Pomelo的聊天室添加time的RPC调用

    为了练手,给聊天应用增加一个rpc调用和一个time类型的服务器,在servers/time/remote/timeRemote.js中,添加如下代码: module.exports.getCurre ...

  7. [svc]简单理解什么是rpc调用?跟restapi有何区别?

    什么是rpc调用 restapi调用方式是对数据的crud. 常见的我们写flash写个api,或者借助django drf写个标准的resetapi,一个url可以借助httpget post pu ...

  8. RPC调用与GC垃圾回收

    RPC调用 多个服务协同完成一次业务时,由于业务约束(如红包不符合使用条件.账户余额不足等).系统故障(如网络或系统超时或中断.数据库约束不满足等),都可能造成服务处理过程在任何一步无法继续,使数据处 ...

  9. rpc调用过程

    在openstack中,各个组件之间的调用遵循RESTful风格,而组件内部各服务之间的相互调用采用rpc远程调用,比如nova-conductor和nova-compute rpc原理: 首先了解什 ...

  10. 浅谈RPC调用

    RPC英文全称remote procedure call 翻译成中文的意思就是远程过程调用.RPC的出现其实主要是为了解决分布式系统间的通信透明性的问题. 那什么是分布式系统的通信透明性问题?这个问题 ...

随机推荐

  1. 699. Falling Squares

    On an infinite number line (x-axis), we drop given squares in the order they are given. The i-th squ ...

  2. 基础篇-密码文件.pgpass

    密码文件包含字段 host:port:dbname:user:password port和dbname可以使用*号作通配符 在*nix系统中 ~/.pgpass 在windows系统中 %APPDAT ...

  3. c#之quartz任务调度的使用

    这里讲下,quartz这种任务调度程序的简单使用 这是使用的quartz的3.x 版本 2.x 版本与此稍有区别,可以在网上查看2.x版本教程 使用语言为c# quartz的使用分为几个步骤 创建一个 ...

  4. symbol lookup error: /lib64/libpango-1.0.so.0: undefined symbol: g_log_structured_standard 错误

    通过更新glib2包修复.(yum update glib2)即可 拿走不谢,我也找得好辛苦!!!

  5. JMeter(7) 优化判断返回类型和返回值

    之前判断接口类型和返回值用beanshell,可见JMeter(5)-JMeter之BeanShell使用 优化点 接口测试里面对返回字段的类型验证和值验证为基本需求,将方法导成jar文件,导入之后方 ...

  6. CentOS与Ubuntu修改主机名

    CentOS 1.执行hostname查看主机名 2.hostname + 主机名  使需要修改的主机名立即生效,但是下次重启会失效,故需要执行第三步 3.vim /etc/sysconfig/net ...

  7. [Leetcode]003. Longest Substring Without Repeating Characters

    https://leetcode.com/problems/longest-substring-without-repeating-characters/ public class Solution ...

  8. [Android]解决 Could not read entry xxx from cache taskArtifacts.bin

    Bug 出现 事情是这样的,昨天早晨我正做着项目,坐在我旁边的小伙伴呼唤了我一下,说项目运行不起来了. 我纳闷着,前天的时候还好好的,怎么过了一晚就出问题了.我问他是不是改了什么配置,或者添加了什么东 ...

  9. Codeforces 1165F2(二分内的check)

    要点 二分答案,内部喜闻乐见的拖延策略:对于某个打折玩具,就选最晚的打折时间买,答案并不会变劣,只是购买时间的平移. 注意最晚时间不是预处理的东西,是二分内部的.在mid以内的最晚时间. #inclu ...

  10. webpack分开打包和合并打包的瘦身

    webpack.config.js 记录一下优化webpack的几个点: 1.     devtool: false,   //产品阶段不应该有devtool entry: { bundle : pa ...