public void destroy() { rpcServer.shutdown(); }
public T build() { Preconditions.checkNotNull(serviceInterface); Preconditions.checkNotNull(zkConn); Preconditions.checkNotNull(serviceName); ClientImpl client = new ClientImpl(this.serviceName); client.setZkConn(this.zkConn); client.setClientProxyClass(clientProxyClass); client.setRequestTimeoutMillis(this.requestTimeoutMillis); client.init(); return client.proxyInterface(this.serviceInterface); } }
protected void channelRead0(ChannelHandlerContext ctx, Request msg) throws Exception { String methodName = msg.getMethod(); Object[] params = msg.getParams(); Class<?>[] parameterTypes = msg.getParameterTypes(); long requestId = msg.getRequestId(); Method method = service.getClass().getDeclaredMethod(methodName, parameterTypes); method.setAccessible(true); Object invoke = method.invoke(service, params); Response response = new Response(); response.setRequestId(requestId); response.setResponse(invoke); ctx.pipeline().writeAndFlush(response); }
@Override public Response sendMessage(Class<?> clazz, Method method, Object[] args) { Request request = new Request(); request.setRequestId(atomicLong.incrementAndGet()); request.setMethod(method.getName()); request.setParams(args); request.setClazz(clazz); request.setParameterTypes(method.getParameterTypes()); ChannelWrapper channelWrapper = selectChannel(); Response response = new Response(); RuntimeException runtimeException = new RuntimeException("Channel is not active now"); response.setThrowable(runtimeException); return response; channel = channelWrapper.getChannelObjectPool().borrowObject(); } catch (Exception e) { e.printStackTrace(); Response response = new Response(); RuntimeException runtimeException = new RuntimeException("Channel is not available now"); response.setThrowable(runtimeException); return response; channel.writeAndFlush(request); BlockingQueue<Response> blockingQueue = new ArrayBlockingQueue<Response>(1); ResponseHolder.responseMap.put(request.getRequestId(), blockingQueue); Response response = blockingQueue.poll(requestTimeoutMillis, TimeUnit.MILLISECONDS); if (response == null) {
public void start() { Server build = ServerBuilder.builder().serviceImpl(serviceImpl) .serviceName(serviceName) .zkConn(zkConn).build(); build.start(); rpcServer = new ServerImpl(port, serviceImpl, serviceName); rpcServer.setZkConn(getZkConn()); rpcServer.start(); }
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (hashCodeMethod.equals(method)) { return proxyHashCode(proxy); } if (equalsMethod.equals(method)) { return proxyEquals(proxy, args[0]); } if (toStringMethod.equals(method)) { return proxyToString(proxy); } try { return client.sendMessage(serviceInterface, method, args).getResponse(); } catch (Exception e) { // TODO RPC invoke exception handle throw new SimpleException(e); } } });
public Server build() { Preconditions.checkNotNull(serviceImpl); Preconditions.checkNotNull(serviceName); Preconditions.checkNotNull(zkConn); Preconditions.checkArgument(port > 0); return new ServerImpl(this.port, this.serviceImpl, this.serviceName, this.zkConn); } }
public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception { LOGGER.info("Listen Event {}", event); List<String> newServiceData = children.forPath(serviceZKPath); LOGGER.info("Server {} list change {}", serviceName, newServiceData); // 关闭删除本地缓存中多出的channel for (ChannelWrapper cw : channelWrappers) { String connStr = cw.getConnStr(); if (!newServiceData.contains(connStr)) { cw.close(); LOGGER.info("Remove channel {}", connStr); channelWrappers.remove(cw); } } // 增加本地缓存中不存在的连接 for (String connStr : newServiceData) { boolean containThis = false; for (ChannelWrapper cw : channelWrappers) { if (connStr != null && connStr.equals(cw.getConnStr())) { containThis = true; } } if (!containThis) { addNewChannel(connStr); } } } });
curatorFramework = CuratorFrameworkFactory.newClient(getZkConn(), new ExponentialBackoffRetry(1000, 3)); curatorFramework.start(); for (String connStr : strings) { try { addNewChannel(connStr); } catch (Exception e) { LOGGER.error("Add New Channel Exception", e);
protected void channelRead0(ChannelHandlerContext ctx, Response msg) throws Exception { BlockingQueue<Response> blockingQueue = responseMap.get(msg.getRequestId()); if (blockingQueue != null) { blockingQueue.put(msg); } }
public void close() { if (curatorFramework != null) { curatorFramework.close(); } try { for (ChannelWrapper cw : channelWrappers) { cw.close(); } } finally { eventLoopGroup.shutdownGracefully(); } }
@Override public void shutdown() { LOGGER.info("Shutting down server {}", serviceName); unRegister(); if (curatorFramework != null) { curatorFramework.close(); } started = false; bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); }
@Override public void start() { ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline() .addLast(new LoggingHandler(LogLevel.INFO)) .addLast(new ProtocolDecoder(10 * 1024 * 1024)) .addLast(new ProtocolEncoder()) .addLast(new RpcServerHandler(serviceImpl)) ; } }); try { ChannelFuture sync = bootstrap.bind(port).sync(); registerService(); LOGGER.info("Server Started At {}", port); started = true; this.channel = sync.channel(); } catch (InterruptedException e) { e.printStackTrace(); } }
private void addNewChannel(String connStr) { try { List<String> strings = Splitter.on(":").splitToList(connStr); if (strings.size() != 2) { throw new RuntimeException("Error connection str " + connStr); } String host = strings.get(0); int port = Integer.parseInt(strings.get(1)); ChannelWrapper channelWrapper = new ChannelWrapper(host, port); channelWrappers.add(channelWrapper); LOGGER.info("Add New Channel {}, {}", connStr, channelWrapper); } catch (Exception e) { e.printStackTrace(); } }
private void registerService() { String zkConn = getZkConn(); ip = InetUtil.getLocalIp(); String ipPortStr = ip + ":" + port;
@Override public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { if (hashCodeMethod.equals(method)) { return proxyHashCode(proxy); } if (equalsMethod.equals(method)) { return proxyEquals(proxy, args[0]); } if (toStringMethod.equals(method)) { return proxyToString(proxy); } return client.sendMessage(serviceInterface, method, args).getResponse(); }