服务提供者

服务接口:

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. python读写xlsx

    1使用openpyxl库读写excel xlrd和xlwt处理的是xls文件,单个sheet最大行数是65535,如果有更大需要的,建议使用openpyxl函数,最大行数达到1048576.  如果数 ...

  2. TemplateText TT 在Runtime发生 Could not load type ...... because the format is invalid

    Severity Code Description Project File Line Suppression State Error Running transformation: System.T ...

  3. 如何使用Node.js搭建一个服务器

    在node环境中运行下面的代码 "use strict"; const http = require("http"), path = require(" ...

  4. 封装MySQL的单例,连接数据库并对数据进行增删改查操作

    单例: 一个类只能有一个对象 应用场景:多次请求数据库只需要一个连接对象. 实现:三私一公 1.私有的静态属性用来保存对象的单例2.私有的构造方法用来阻止在类的外部实例化3.私有的__clone阻止在 ...

  5. 黑马MyBatis入门day1

    package com.itheima.domain; /* CREATE TABLE `user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `username ...

  6. C# 流

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...

  7. AtCoder Regular Contest 082 ABCD

    A #include<bits/stdc++.h> using namespace std; ]; int n,m; int main(){ cin>>n>>m; ...

  8. cachecloud:Redis云管理平台

    https://github.com/sohutv/cachecloud 一.CacheCloud是做什么的 CacheCloud提供一个Redis云管理平台:实现多种类型(Redis Standal ...

  9. CoreDataDemo

    // User.h // CoreDataDemo // // Created by gaokunpeng on 15/2/4. // Copyright (c) 2015年 qianfeng. Al ...

  10. swift3.0 项目引导页

    项目引导页并不难,使用 UICollectionView就可以完成, 1.首先获取应用程序的版本号,并存入本地,每次有新版本号,和存入本地的版本号,相比较 fileprivate func setup ...