自己动手实现RPC

一、需求:用户管理系统(UMS),仓库管理系统(WMS),订单管理系统(OMS)

现在OMS有一张订单表:【订单id,用户id,商品id,订单状态,订单时间】,需要在客户端展示此订单对应的用户详情和商品详情

二、接口API整理:在OMS中,需要根据用户id在UMS中查询用户详情和根据商品id在WMS中查询商品详情

1.User selectUserById(long id)

2.Product selectProductById(long id)

三、接口调用架构图:

四、代码实现

 1.工程结构

2.代码实现

// OMS系统代码
public
class Order { private Long id; // 商品id private Long productId; // 用户id private Long userId; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getProductId() { return productId; } public void setProductId(Long productId) { this.productId = productId; } public Long getUserId() { return userId; } public void setUserId(Long userId) { this.userId = userId; } @Override public String toString() { return "Order{" + "id=" + id + ", productId=" + productId + ", userId=" + userId + '}'; } } public class OrderService { public Order selectOrderById(long id){ Order order = new Order(); order.setId(id); order.setUserId(1l); order.setProductId(1L); return order; } } public class Main { public static void main(String[] args) { // 获取订单详情 OrderService orderService = new OrderService(); Order order = orderService.selectOrderById(1L); System.out.println("订单信息:" + order); // 根据商品id获取商品 ProductService productService = (ProductService) rpcHandle(ProductService.class, "127.0.0.1", 8888); Product product = productService.selectProductById(order.getProductId()); System.out.println("商品信息:" + product); // 根据用户id获取用户 UserService userService = (UserService) rpcHandle(UserService.class, "127.0.0.1", 9999); User user = userService.selectUserById(order.getUserId()); System.out.println("用户信息:" + user); } /** * RPC远程调用实现 */ public static Object rpcHandle(final Class clazz, final String host, final int port) { return Proxy.newProxyInstance(clazz.getClassLoader(), new Class[]{clazz}, new InvocationHandler() { public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Socket socket = new Socket(host, port); // 想要调用远程类的某个方法,必须要知道类名称,方法名称,参数类型,参数 String apiClassName = clazz.getName(); String methodName = method.getName(); Class[] parameterTypes = method.getParameterTypes(); ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream()); objectOutputStream.writeUTF(apiClassName); objectOutputStream.writeUTF(methodName); objectOutputStream.writeObject(parameterTypes); objectOutputStream.writeObject(args); objectOutputStream.flush(); ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream()); Object object = objectInputStream.readObject(); if (null != objectInputStream ){ objectInputStream.close(); } if (null != objectOutputStream){ objectOutputStream.close(); } if (null != socket){ socket.close(); } return object; } } ); } }
// WMS代码
public class Product implements Serializable {
    private Long id;
    private String name;
    private Double price;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Double getPrice() {
        return price;
    }

    public void setPrice(Double price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "Product{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", price=" + price +
                '}';
    }
}

public interface ProductService {

    /**
     * 根据商品ID查询商品信息
     *
     * @param id:商品id
     * @return
     */
    Product selectProductById(long id);
}

public class ProductServiceImpl implements ProductService {
    public Product selectProductById(long id) {
        Product product = new Product();
        product.setId(id);
        product.setName("CAMEL运动鞋");
        product.setPrice(299.0);
        return product;
    }
}

public class Main {
    public static void main(String[] args) {
        try {
            ServerSocket serverSocket = new ServerSocket(8888);
            while (true) {
                Socket socket = serverSocket.accept();
                ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
                // 读取网络协议
                String apiClassName = objectInputStream.readUTF();
                String methodName = objectInputStream.readUTF();
                Class[] parameterTypes = (Class[]) objectInputStream.readObject();
                Object[] argsMethod = (Object[]) objectInputStream.readObject();

                Class clazz = null;
                // 服务注册:API到具体实现的映射关系
                if (apiClassName.equals(ProductService.class.getName())) {
                    clazz = ProductServiceImpl.class;
                }
                ObjectOutputStream objectOutputStream = null;
                if (null != clazz) {
                    Method method = clazz.getMethod(methodName, parameterTypes);
                    Object invoke = method.invoke(clazz.newInstance(), argsMethod);
                    objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
                    objectOutputStream.writeObject(invoke);
                    objectOutputStream.flush();
                }
                // 关闭资源
                if (null != objectInputStream) {
                    objectInputStream.close();
                }
                if (null != objectOutputStream) {
                    objectOutputStream.close();
                }
                if (null != socket) {
                    socket.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
// UUMS代码
public class User implements Serializable {
    private Long id;
    private String name;
    private Integer age;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age='" + age + '\'' +
                '}';
    }
}

public interface UserService {

    /**
     * 根据用户id,查询用户
     * @param id:用戶id
     * @return
     */
    User selectUserById(Long id);
}

public class UserServiceImpl implements UserService {
    public User selectUserById(Long id) {
        User user = new User();
        user.setId(id);
        user.setName("Jack Tang");
        user.setAge(20);
        return user;
    }
}

public class UserServiceImpl implements UserService {
    public User selectUserById(Long id) {
        User user = new User();
        user.setId(id);
        user.setName("Jack Tang");
        user.setAge(20);
        return user;
    }
}

public class Main {
    public static void main(String[] args) {
        try {
            ServerSocket serverSocket = new ServerSocket(9999);
            while (true) {
                Socket socket = serverSocket.accept();
                ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
                String apiClassName = objectInputStream.readUTF();
                String methodName = objectInputStream.readUTF();
                Class[] parameterTypes = (Class[]) objectInputStream.readObject();
                Object[] argsMethod = (Object[]) objectInputStream.readObject();

                Class clazz = null;
                if (apiClassName.equals(UserService.class.getName())){
                    clazz = UserServiceImpl.class;
                }
                ObjectOutputStream objectOutputStream = null;
                if (null != clazz) {
                    Method method = clazz.getMethod(methodName, parameterTypes);
                    Object invoke = method.invoke(clazz.newInstance(), argsMethod);
                    objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
                    objectOutputStream.writeObject(invoke);
                    objectOutputStream.flush();
                }
                // 关闭资源
                if (null != objectInputStream) {
                    objectInputStream.close();
                }
                if (null != objectOutputStream) {
                    objectOutputStream.close();
                }
                if (null != socket) {
                    socket.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

 

posted @ 2018-09-26 23:31  麻雀虽小五脏俱全  阅读(447)  评论(0编辑  收藏  举报