RPC Java to achieve a simple process

RPC Java to achieve a simple process

RPC is a remote procedure call (Remote Procedure Call) abbreviation commonly used in distributed systems architecture. In a distributed system, the system components will generally be decomposed according to the needs, deployed on different servers, can be performed between the system components are interconnected by a call RPC.
RPC can be reduced degree of coupling between system functions, each of the system service components distributed on different servers, can be independently maintained and upgraded;
RPC can improve system scalability and robustness, via a uniform interface control, and multiplexing of extensions ;

Case Design: Design a calculator, a calculator to realize internal method to get results through long-distance calls
  1. Design Calculator interface methods and implementation class;
  2. Provided serialized object calculator operands and packaging method;
  3. Internal implementation class encapsulates the calculator object serialization and transmission to the Server side waiting to acquire the execution result returned from the Server;
  4. Server side through deserialized package object acquisition method of the operands and corresponding method for local calls;
  5. Server-side local method execution result returned Client-side package;
  6. Client-Server receiving terminal returns an execution result to the method call to complete the calculation of the calculator.
Client-side configuration classes:
1, for the user class
public class Client {
    public static void main(String[] args) throws ClassNotFoundException
    {
        //创建计算器
        Calculator calculator=new CalculatorRemoteImpl();
        //调用计算器加方法
        int result=calculator.add(52,56);
        System.out.println(result);
    }
}
2, calculator interfaces:
public interface Calculator {

    int add(int i, int j);

}
3, implementation class Calculator:

Achieve internal class value output by the sequence of wrapped objects is sent to the Server side, the receiving side Server returns an execution result as a method.

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class CalculatorRemoteImpl implements Calculator{
    public int add(int a,int b)
    {
        Socket socket = null;
        ObjectOutputStream objectOutputStream = null;
        ObjectInputStream objectInputStream = null;
        try {
            socket = new Socket("127.0.0.1",9000);
            //封装计算器操作数,实现可序列化
            CalculateRpcRequest calculateRpcRequest = new CalculateRpcRequest(a,b,"add");
            //对象输出流,将封装数据的对象序列化写入Socket
            objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
            objectOutputStream.writeObject(calculateRpcRequest);
            //对象输入流,读入Socket中数据反序列化转换为对象
            objectInputStream = new ObjectInputStream(socket.getInputStream());
            Object response = null;
            try {
                response = objectInputStream.readObject();
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            if(response instanceof Integer)
            {
                return (Integer)response;
            }
            else
            {               
                throw new InternalError();              
            }
            
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        finally
        {
            if(socket!=null)
            {
                try {
                    socket.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if(objectOutputStream!=null)
            {
                try {
                    objectOutputStream.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if(objectInputStream!=null)
            {
                try {
                    objectInputStream.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        return 0;
    }
}
4 serialized object, the operands and encapsulation methods
import java.io.Serializable;

public class CalculateRpcRequest implements Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    int A;
    int B;
    String method;
    
    public CalculateRpcRequest(int A, int B, String method) {
        this.A=A;
        this.B=B;
        this.method = method;
    }
}
Remote Server side:
1, for packaging objects deserialized

Note: serialized objects Client-side and Server side must be consistent with the full class name, package name and class name that is identical to successfully convert deserialized object.

import java.io.Serializable;

public class CalculateRpcRequest implements Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    int A;
    int B;
    String method;
    
    public CalculateRpcRequest(int A, int B, String method) {
        this.A=A;
        this.B=B;
        this.method = method;
    }
    public int getA() {
        return A;
    }
    public void setA(int a) {
        A = a;
    }
    public int getB() {
        return B;
    }
    public void setB(int b) {
        B = b;
    }
    public String getMethod() {
        return method;
    }
    public void setMethod(String method) {
        this.method = method;
    }
}
2, the remote end calculator interfaces:
public interface Calculator {

    int add(int i, int j);

}
3, the remote side implementation class Calculator:
public class CalculatorImpl implements Calculator {

    @Override
    public int add(int i, int j) {      
        return i+j;
    }
}
4, the remote terminal receives Client requests local method call and returns the results of

Client-Server receives the request, acquires packaged object property values, local method calls and returns the result.

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import Test.RPC.consumer.CalculateRpcRequest;

public class Server {
    private static Calculator calculator=new CalculatorImpl();
    public static void main(String[] args)
    {
        ServerSocket listener = null;
        ObjectInputStream objectInputStream = null;
        ObjectOutputStream objectOutputStream = null;
        try {
            listener = new ServerSocket(9000);
            while(true)
            {
                //监听连接的TCP Client
                Socket socket=listener.accept();
                //对象输入流,读入Socket中数据反序列化转换为对象
                objectInputStream = new ObjectInputStream(socket.getInputStream());
                try {
                    Object object = objectInputStream.readObject();
                    int result=0;
                    if(object instanceof CalculateRpcRequest)
                    {
                        CalculateRpcRequest calculateRpcRequest=(CalculateRpcRequest)object;
                        if("add".equals(calculateRpcRequest.getMethod()))
                        {
                            result=calculator.add(calculateRpcRequest.getA(), calculateRpcRequest.getB());
                            
                        }
                        else
                        {
                            throw new UnsupportedOperationException();
                        }
                    }
                    //对象输出流,将封装数据的对象序列化写入Socket
                    objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
                    objectOutputStream.writeObject(new Integer(result));
                } catch (ClassNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                finally
                {
                    socket.close();
                }
            }
            
            
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        finally
        {
            if(listener!=null)
            {
                try {
                    listener.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if(objectInputStream!=null)
            {
                try {
                    objectInputStream.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if(objectOutputStream!=null)
            {
                try {
                    objectOutputStream.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
}
to sum up

1, an object serialization by the basic realization of the RPC process, service registration for senior RPC framework, load balancing, and other mechanisms not involving paper for reference only.
2, code references: http: //bridgeforyou.cn/2018/05/04/How-to-Implement-a-Simple-RPC/

Guess you like

Origin www.cnblogs.com/zijunempire/p/11682170.html