JKAS RPC

RPC(Remote Procedure Call Protocol)远程过程调用协议,通过网络从远程计算机上请求调用某种服务。它是一种通过网络从远程计算机程序上请求服务,而不需要了解底层网络技术的协议。

一、配置

[RPC]

;是否启用RPC
rpc_enable=1

;RPC服务所在包名
rpc_package=test.z.rpc
;RPC端口

rpc_port=9889

 

二、服务命名

服务由接口文件和实现文件构成

命名方式为服务名可自行命名,遵循驼峰命名规则

实现名由服务接口名+Impl方式命名

 

如:

Hello为服务接口名

HelloImpl为服务实现命名

 

 

三、案例

1、服务端

package test.z.rpc;
public interface Hello {
    String sayHello(String string);
}

 

package test.z.rpc;
public class HelloImpl implements Hello{
 
    public String sayHello(String string) {
        // TODO Auto-generated method stub
        return "你好:" + string;
    }
}

 

2、客户端(只支持JAVA)

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.InetSocketAddress;
import java.net.Socket;
 
import test.z.rpc.Hello;
 
public class RpcClient<T> implements InvocationHandler {
    private Socket socket = null;
 ObjectOutputStream output = null;
    ObjectInputStream input = null;
    private  Class<T> serviceInterface;
    private InetSocketAddress addr;
 
    public RpcClient(String ip,String port) {
       
        this.addr = new InetSocketAddress(ip, Integer.parseInt ( port ));
    }
 
    public T getClientIntance(Class<T> serviceInterface){
        this.serviceInterface = serviceInterface;
  return (T) Proxy.newProxyInstance (serviceInterface.getClassLoader(),new Class<?>[]{serviceInterface},this);
    }

 public void conn()
 { try {
            socket = new Socket();
            socket.connect(addr);
       }
    catch(Exception e)
  {
  }
 }

 public void close()
 {try{
  
   if (socket != null) socket.close();
   if (output != null) output.close();
         if (input != null) input.close();
     }
  catch(Exception e)
  {
  }
 }
 
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        try {
            conn();
            output = new ObjectOutputStream(socket.getOutputStream());
            output.writeUTF(serviceInterface.getName());
            output.writeUTF(method.getName());
            output.writeObject(method.getParameterTypes());
            output.writeObject(args);
            input = new ObjectInputStream(socket.getInputStream());
            return input.readObject();
        } finally {
           close();
        }
    }
 
    public static void main(String[] args) {
        RpcClient client = new RpcClient<>("localhost","9889");
        Hello hello = (Hello) client.getClientIntance (Hello.class);
        System.out.println (hello.sayHello ( "socket hellorpc" ));
    }
}