java网络编程实战 - 运用TCP通讯思想

/**
* @author andychen https://blog.51cto.com/14815984
* @description:RPC服务端框架部分
* */
public class ProducerFramework {
   //服务监听端口
   private final int port;
   //服务在服务端缓存
   private final static Map<String,Class<?>> cachedService = new ConcurrentHashMap<>();
   //服务处理任务池
   private final static ExecutorService taskPool = Executors.newFixedThreadPool(
           Runtime.getRuntime().availableProcessors()+1);
   public ProducerFramework(int port) {this.port = port;}

   /**
    * 注册服务核心业务
    * @param service 服务接口类
    * @param serviceImpl 服务实现类
    */
   public void register(Class<?> service, Class<?> serviceImpl) {
       InputStream inputStream = null;
       OutputStream outputStream = null;
       Socket socket = new Socket();
       try {
           //连接注册中心
           socket.connect(new InetSocketAddress(Constant.REG_CENTER_HOST, Constant.REG_CENTER_PORT));
           //服务名称
           String serviceName = service.getName();
           outputStream = new ObjectOutputStream(socket.getOutputStream());
           ((ObjectOutputStream) outputStream).writeUTF(serviceName);
           //标记服务注册
           ((ObjectOutputStream) outputStream).writeBoolean(false);
           //服务所在主机
           ((ObjectOutputStream) outputStream).writeUTF(Constant.SERVER_HOST);
           //服务监听端口
           ((ObjectOutputStream) outputStream).writeInt(this.port);
           //刷服务到注册中心
           outputStream.flush();
           //获取注册结果
           inputStream = new ObjectInputStream(socket.getInputStream());
           if (((ObjectInputStream) inputStream).readBoolean()) {
               //缓存在服务端
               cachedService.put(serviceName, serviceImpl);
               System.out.println("服务[" + serviceName + "],注册成功!");
           } else {
               System.out.println("服务[" + serviceName + "],注册失败,请查看日志!");
           }
       } catch (Exception e) {
           e.printStackTrace();
       } finally {
           try {
               if (null != inputStream) {
                   inputStream.close();
                   inputStream = null;
               }
               if (!socket.isClosed()) {
                   socket.close();
               }
           } catch (IOException e) {
               e.printStackTrace();
           }
           socket = null;
       }
   }

   /**
    * 服务运行

猜你喜欢

转载自www.cnblogs.com/weiwei186/p/13171808.html