@Override public CompletionStage<NodeConnectionReport> closeConnectionAsync( SocketAddress connection, CloseType type) { Optional<Channel> channel = this.clientChannelGroup .stream() .filter(c -> c.remoteAddress().equals(connection)) .findFirst(); if (channel.isPresent()) { ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE); channelGroup.add(channel.get()); ClusterConnectionReport clusterReport = new ClusterConnectionReport(getCluster().getId()); NodeConnectionReport report = clusterReport.addNode(this, Collections.singletonList(connection), getAddress()); return closeChannelGroup(channelGroup, type).thenApply(f -> report); } else { CompletableFuture<NodeConnectionReport> failedFuture = new CompletableFuture<>(); failedFuture.completeExceptionally(new IllegalArgumentException("Not found")); return failedFuture; } }
public WhirlpoolMessageHandler(ChannelGroup channels) { this.channels = channels; ReadIncomingCallable toClientCallable = new ReadIncomingCallable(); FutureTask<String> toClientPc = new FutureTask<>(toClientCallable); ExecutorService toClientExecutor = Executors.newSingleThreadExecutor( new ThreadFactoryBuilder() .setDaemon(true) .setNameFormat("to-client-%d") .build() ); toClientExecutor.execute(toClientPc); SendCommandsToKafkaCallable toKafkaCallable = new SendCommandsToKafkaCallable(); FutureTask<String> toKafka = new FutureTask<>(toKafkaCallable); ExecutorService toKafkaExecutor = Executors.newSingleThreadExecutor( new ThreadFactoryBuilder() .setDaemon(true) .setNameFormat("to-kafka-%d") .build() ); toKafkaExecutor.execute(toKafka); }
private void sendReq(String btyimei) { Battery battery = batteryService.fetchBtyByIMEI(btyimei); if (battery == null) { logger.error("电池不存在, " + btyimei); return; } boolean hasConn = false; ChannelGroup channelGroup = SamBtyDataHandler.getChannels(); for (Channel c : channelGroup) { String imei = (String) c.attr(AttributeKey.valueOf("IMEI")).get(); logger.info("已经连接的imei:" + imei); if (imei != null && imei.equals(battery.getImei())) { c.writeAndFlush("tellme" + imei + "\n"); hasConn = true; } } if (!hasConn) { logger.error("未获取到长连接, " + btyimei); } }
@Override public boolean chat(String deviceImei, String chatType) { Battery battery = batteryService.fetchBtyByIMEI(deviceImei); if (battery == null) { logger.error("数据库中设备不存在, 设备Imei卡号:{}", deviceImei); return false; } boolean hasConn = false; ChannelGroup channelGroup = SamBtyDataHandler.getChannels(); for (Channel c : channelGroup) { String imei = (String) c.attr(AttributeKey.valueOf("IMEI")).get(); logger.info("已经连接设备的imei:{}", imei); if (imei != null && imei.equals(battery.getImei())) { String msg = chatType + imei + "\n"; c.writeAndFlush(msg); hasConn = true; } } if (!hasConn) { logger.error("未获取到长连接, 设备Imei卡号:{}", deviceImei); } return hasConn; }
@Test public void initChannel_adds_OpenChannelLimitHandler_after_RequestInfoSetterHandler_and_uses_cached_ChannelGroup() { // given HttpChannelInitializer hci = basicHttpChannelInitializer(null, 0, 42, false, null, null); // when hci.initChannel(socketChannelMock); // then ArgumentCaptor<ChannelHandler> channelHandlerArgumentCaptor = ArgumentCaptor.forClass(ChannelHandler.class); verify(channelPipelineMock, atLeastOnce()).addLast(anyString(), channelHandlerArgumentCaptor.capture()); List<ChannelHandler> handlers = channelHandlerArgumentCaptor.getAllValues(); Pair<Integer, RequestInfoSetterHandler> requestInfoSetterHandler = findChannelHandler(handlers, RequestInfoSetterHandler.class); Pair<Integer, OpenChannelLimitHandler> openChannelLimitHandler = findChannelHandler(handlers, OpenChannelLimitHandler.class); assertThat(requestInfoSetterHandler, notNullValue()); assertThat(openChannelLimitHandler, notNullValue()); assertThat(openChannelLimitHandler.getLeft(), is(requestInfoSetterHandler.getLeft() + 1)); // and then ChannelGroup expectedChannelGroup = extractField(hci, "openChannelsGroup"); ChannelGroup actualChannelGroup = (ChannelGroup) Whitebox.getInternalState(openChannelLimitHandler.getRight(), "openChannelsGroup"); assertThat(actualChannelGroup, is(expectedChannelGroup)); }
@Override public void channelActive(ChannelHandlerContext ctx) throws Exception { Channel channel = ctx.channel(); ChannelGroup channelGroup = getServerImpl().getChannelGroup(); ctx.channel().attr(ServerImpl.REQUEST_CONNECTION_ID).set(channel.id().asLongText()); channelGroup.add(channel); super.channelActive(ctx); }
/** * Send to group. * * @param groupName * the group name * @param message * the message * @param except * the except */ public void sendToGroup(String groupName, byte[] message, SystemIdKey... except) { ChannelGroup group = getGroup(groupName); if (group == null) return; group.forEach(c -> { try { AbstractRegistryKey<?> systemId = getKeyForChannel(c); if (!excepted(systemId, except)) send(systemId, message); } catch (Exception e) { log.error("Unexpected exception sending message to {}", c, e); } }); }
/** * Send to group. * * @param groupName * the group key * @param message * the message * @param matcher * the matcher * @param listeners * the listeners */ public void sendToGroup(String groupName, byte[] message, ChannelMatcher matcher, ChannelFutureListener... listeners) { groupCheck(groupName); checkMessage(message); if (!groups.containsKey(groupName)) { log.warn("No group {} to send message {}", groupName, message); return; } ChannelGroup group = groups.get(groupName); ChannelFutureListener[] all = utils.prependArray(f -> log((ChannelGroupFuture) f, groupName), listeners); ChannelGroupFuture cf = group.writeAndFlush(message, matcher); cf.addListeners(all); }
public NettyServer(final int port, final ServiceRegistry registry, final StaticPathResolver staticResolver, final ChannelGroup activeChannels, final String contextPath, final String applicationName, final boolean acceptKeepAlive, final long idleTimeoutMs, final boolean supportZip, final MetricFactory metricFactory, final int maxContentLength, final long requestTimeoutMs) { System.setProperty("com.outbrain.web.context.path", contextPath); this.port = port; this.staticResolver = staticResolver; this.activeChannels = activeChannels; this.contextPath = contextPath; this.applicationName = applicationName; this.marshallerRegistry = registry.getMarshallerRegistry(); this.dispatcher = new ServiceDispatcher(registry, marshallerRegistry); this.nioGroup = new NioEventLoopGroup(); this.acceptKeepAlive = acceptKeepAlive; this.supportZip = supportZip; this.metricFactory = metricFactory; this.maxContentLength = maxContentLength; this.requestTimeoutMs = requestTimeoutMs; this.idleTimeoutMs = idleTimeoutMs; registry.logRegisteredEndpoints(); }
/** * 实际发送消息方法 * * @param pushMessage * @param status * @param messageInfo * @param deviceId * @return */ private MessagePushedInfo makeMessageInfoToDevice(ChannelGroup mchannels, MessageInfo messageInfo, DeviceInfo deviceInfo) { // System.out.println("makeMessageInfoToDevice come in!"); // 获取设备消息发送对象 MessagePushedInfo messagePushedInfo = getMessagePushedInfo(messageInfo, deviceInfo); if (messagePushedInfo != null) { // 发送消息 if (deviceInfo != null && deviceInfo.getIsOnline() == DEVICE_ONLINE_YES) { // 如果设备在线 则添加发送通道 ChannelDeviceInfo channelDeviceInfo = this.getChannelDeviceInfoFromCache(deviceInfo.getDeviceId()); // System.out.println("makeMessageInfoToDevice channelDeviceInfo=" + channelDeviceInfo); Channel channel = channelDeviceInfo == null ? null : channelDeviceInfo.getChannel(); if (channel != null && channel.isWritable()) { mchannels.add(channel); } else { return null; } } } return messagePushedInfo; }
@Test public void testMasterSlaveSentinelConnectionCount() throws Exception { ChannelGroup channels = (ChannelGroup) ReflectionTestUtils.getField(sentinelClient, "channels"); int count = channels.size(); StatefulRedisMasterSlaveConnection<String, String> connection = MasterSlave.connect(sentinelClient, new Utf8StringCodec(), sentinelUri); connection.sync().ping(); connection.setReadFrom(ReadFrom.SLAVE); slaveCall(connection); assertThat(channels.size()).isEqualTo(count + 2 /* connections */ + 1 /* sentinel connections */); connection.close(); }
@Test public void testMasterSlaveSentinelClosesSentinelConnections() throws Exception { ChannelGroup channels = (ChannelGroup) ReflectionTestUtils.getField(sentinelClient, "channels"); int count = channels.size(); StatefulRedisMasterSlaveConnection<String, String> connection = MasterSlave.connect(sentinelClient, new Utf8StringCodec(), sentinelUri); connection.sync().ping(); connection.setReadFrom(ReadFrom.SLAVE); slaveCall(connection); connection.close(); assertThat(channels.size()).isEqualTo(count); }
public MetricBatcher(final MetricFactory metricFactory, final int batchBufferCapacity, final ChannelGroup activeChannels, final int maxChannelIdleTime) { Preconditions.checkArgument(maxChannelIdleTime > 0, "maxChannelIdleTime must be greater than 0"); this.maxChannelIdleTime = maxChannelIdleTime; Preconditions.checkNotNull(metricFactory, "metricFactory may not be null"); this.batchBufferCapacity = batchBufferCapacity; this.activeChannels = Preconditions.checkNotNull(activeChannels, "activeChannels must not be null"); prepareNewBatch(); final String component = getClass().getSimpleName(); connectionCounter = metricFactory.createCounter(component, "connections"); metricsCounter = metricFactory.createCounter(component, "metricsReceived"); unexpectedErrorCounter = metricFactory.createCounter(component, "unexpectedErrors"); ioErrorCounter = metricFactory.createCounter(component, "ioErrors"); idleChannelsClosed = metricFactory.createCounter(component, "idleChannelsClosed"); metricSize = metricFactory.createHistogram(component, "metricSize", false); try { metricFactory.registerGauge(component, "batchSize", new Gauge<Integer>() { @Override public Integer getValue() { return lastBatchSize.get(); } }); } catch (IllegalArgumentException e) { // ignore metric already exists } }
private static CompletableFuture<Void> closeChannelGroup( ChannelGroup channelGroup, CloseType closeType) { switch (closeType) { case DISCONNECT: return completable(channelGroup.disconnect()); default: return CompletableFuture.allOf( channelGroup .stream() .map( c -> { CompletableFuture<Void> f; Function<SocketChannel, ChannelFuture> shutdownMethod = closeType == CloseType.SHUTDOWN_READ ? SocketChannel::shutdownInput : SocketChannel::shutdownOutput; if (c instanceof SocketChannel) { f = completable(shutdownMethod.apply((SocketChannel) c)); } else { logger.warn( "Got {} request for non-SocketChannel {}, disconnecting instead.", closeType, c); f = completable(c.disconnect()); } return f; }) .collect(Collectors.toList()) .toArray(new CompletableFuture[] {})); } }
public RedisChannelInitializer(Bootstrap bootstrap, RedisClientConfig config, RedisClient redisClient, ChannelGroup channels, Type type) { super(); this.bootstrap = bootstrap; this.config = config; this.redisClient = redisClient; this.channels = channels; this.type = type; }
public void init(WebAppConfiguration webapp, ChannelGroup sharedChannelGroup) { this.webAppConfig = webapp; this.sharedChannelGroup = sharedChannelGroup; this.initServletContext(); this.initContextListeners(); this.initFilters(); this.initServlets(); }
public void sendToSubscribers(String topic, String message) { ChannelGroup connections; synchronized(mTopicsSubscribers) { connections = mTopicsSubscribers.get(topic); } if (connections == null) return; try { connections.writeAndFlush(new MessagePacket(topic, message, System.currentTimeMillis())); } catch (Exception e) {} }
private void sendReq(String Imei) { Battery battery = batteryService.fetchBtyByIMEI(Imei); if (battery == null) { logger.error("电池不存在, " + Imei); return; } boolean hasConn = false; ChannelGroup channelGroup = SamBtyDataHandler.getChannels(); for (Channel c : channelGroup) { String imei = (String) c.attr(AttributeKey.valueOf("IMEI")).get(); logger.info("已经连接的imei:" + imei); if (imei != null && imei.equals(battery.getImei())) { c.writeAndFlush("tellme" + imei + "\n"); hasConn = true; } } if (!hasConn) { logger.error("未获取到长连接, " + Imei); } // ConcurrentHashMap<String, Channel> map = // SamBtyDataHandler.getChannelMap(); // Channel channel = map.get(battery.getImei()); // if (channel == null) { // logger.error("未获取到长连接, " + simNo); // } // // channel.writeAndFlush("tellme\r\n"); }
public OpenChannelLimitHandler(ChannelGroup openChannelsGroup, int maxOpenChannelsThreshold) { if (openChannelsGroup == null) throw new IllegalArgumentException("openChannelsGroup cannot be null"); if (maxOpenChannelsThreshold < 1) throw new IllegalArgumentException("maxOpenChannelsThreshold must be at least 1"); this.openChannelsGroup = openChannelsGroup; this.maxOpenChannelsThreshold = maxOpenChannelsThreshold; }
@Before public void beforeMethod() { channelMock = mock(Channel.class); ctxMock = mock(ChannelHandlerContext.class); tooManyOpenConnectionsAttributeMock = mock(Attribute.class); doReturn(channelMock).when(ctxMock).channel(); doReturn(tooManyOpenConnectionsAttributeMock).when(channelMock) .attr(TOO_MANY_OPEN_CONNECTIONS_THIS_CHANNEL_SHOULD_CLOSE); doReturn(true).when(channelMock).isOpen(); eventLoopMock = mock(EventLoop.class); closeFutureMock = mock(ChannelFuture.class); doReturn(eventLoopMock).when(channelMock).eventLoop(); doReturn(closeFutureMock).when(channelMock).closeFuture(); doubleCheckScheduledFutureMock = mock(ScheduledFuture.class); doubleCheckRunnableCaptor = ArgumentCaptor.forClass(Runnable.class); closeFutureListenerCaptor = ArgumentCaptor.forClass(GenericFutureListener.class); doReturn(doubleCheckScheduledFutureMock).when(eventLoopMock) .schedule(any(Runnable.class), anyLong(), any(TimeUnit.class)); doReturn(false).when(doubleCheckScheduledFutureMock).isDone(); channelGroupMock = mock(ChannelGroup.class); maxOpenChannelsThreshold = 42; handler = new OpenChannelLimitHandler(channelGroupMock, maxOpenChannelsThreshold); }
private int getNumberOfConnectedClients() { final Server server = getComponent(Server.KEY); if (server == null) { Log.i(TAG, "Container not yet connected."); return 0; } ChannelGroup activeChannels = server.getActiveChannels(); return activeChannels.size(); }
public ChannelMediator(Channel clientChannel, final ProxyModeControllerFactory proxyModeControllerFactory, final NioEventLoopGroup upstreamWorkerGroup, final int timeout, final ChannelGroup channelGroup) { _clientChannel = clientChannel; _proxyModeControllerFactory = proxyModeControllerFactory; _upstreamWorkerGroup = upstreamWorkerGroup; _serverConnectionIdleTimeoutMsec = timeout; _allChannelGroup = channelGroup; }
private static void runTest(ThreadPerChannelEventLoopGroup loopGroup) throws InterruptedException { int taskCount = 100; EventExecutor testExecutor = new TestEventExecutor(); ChannelGroup channelGroup = new DefaultChannelGroup(testExecutor); while (taskCount-- > 0) { Channel channel = new EmbeddedChannel(NOOP_HANDLER); loopGroup.register(channel, new DefaultChannelPromise(channel, testExecutor)); channelGroup.add(channel); } channelGroup.close().sync(); loopGroup.shutdownGracefully(100, 200, TimeUnit.MILLISECONDS).sync(); assertTrue(loopGroup.isTerminated()); }
IotChannelGroupFuture(ChannelGroup group, Map<Channel, ChannelFuture> futures, EventExecutor executor) { super(executor); this.group = group; this.futures = Collections.unmodifiableMap(futures); for (ChannelFuture f: this.futures.values()) { f.addListener(childListener); } // Done on arrival? if (this.futures.isEmpty()) { setSuccess0(); } }
/** * Send to group. * * @param groupName * the group name * @param message * the message * @param listeners * the listeners */ public void sendToGroup(String groupName, byte[] message, ChannelFutureListener... listeners) { ChannelGroup group = getGroup(groupName); if (group == null) return; group.forEach(c -> { try { send(getKeyForChannel(c), message, listeners); } catch (Exception e) { log.error("Unexpected exception sending message to {}", c, e); } }); }
/** * Gets the group. * * @param groupName * the group name * @return the group */ public ChannelGroup getGroup(String groupName) { ChannelGroup group = registry.getGroup(groupName); if (group == null) { log.warn("No group {}", groupName); return null; } return group; }
/** * Removes the channel from the group specified by groupName. * * @param groupName * the group key * @param channel * the channel */ public void removeFromGroup(String groupName, Channel channel) { groupCheck(groupName, channel); ChannelGroup group = groups.get(groupName); if (group == null) return; group.remove(channel); }
/** * Removes the group. * * @param groupName * the group key */ public void removeGroup(String groupName) { groupCheck(groupName); if (!groups.containsKey(groupName)) return; ChannelGroup group = groups.remove(groupName); group.clear(); }
/** * Send the message to a specific group. * * @param groupName * the group key * @param message * the message * @param listeners * the listeners */ public void sendToGroup(String groupName, String message, ChannelFutureListener... listeners) { groupCheck(groupName); if (!groups.containsKey(groupName)) { log.warn("No group {} to send message {}", groupName, message); return; } ChannelGroup group = groups.get(groupName); ChannelFutureListener[] all = utils.prependArray(f -> log((ChannelGroupFuture) f, groupName), listeners); ChannelGroupFuture cf = group.writeAndFlush(message); cf.addListeners(all); }
/** * Send the message to a specific group. * * @param groupName * the group key * @param message * the message * @param listeners * the listeners */ public void sendToGroup(String groupName, byte[] message, ChannelFutureListener... listeners) { groupCheck(groupName); if (!groups.containsKey(groupName)) { log.warn("No group {} to send message {}", groupName, message); return; } ChannelGroup group = groups.get(groupName); ChannelFutureListener[] all = utils.prependArray(f -> log((ChannelGroupFuture) f, groupName), listeners); ChannelGroupFuture cf = group.writeAndFlush(message); cf.addListeners(all); }
/** * Send to group. * * @param groupName * the group key * @param message * the message * @param matcher * the matcher * @param listeners * the listeners */ public void sendToGroup(String groupName, String message, ChannelMatcher matcher, ChannelFutureListener... listeners) { groupCheck(groupName); if (!groups.containsKey(groupName)) { log.warn("No group {} to send message {}", groupName, message); return; } ChannelGroup group = groups.get(groupName); ChannelFutureListener[] all = utils.prependArray(f -> log((ChannelGroupFuture) f, groupName), listeners); ChannelGroupFuture cf = group.writeAndFlush(message, matcher); cf.addListeners(all); }
protected ActiveMQChannelHandler(final ChannelGroup group, final BufferHandler handler, final BaseConnectionLifeCycleListener<?> listener) { this.group = group; this.handler = handler; this.listener = listener; }
public ChannelGroup getGroup() { ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE); if(!CollectionUtils.isEmpty(items)) { items.forEach((itemId, channel) -> channelGroup.add(channel)); } return channelGroup; }
public ChannelGroup getGroup(String... itemIds) { if(ArrayUtils.isEmpty(itemIds)) { return DEFAULT; } ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE); if(!CollectionUtils.isEmpty(items)) { items.entrySet().stream().filter(entry -> ObjectCompare.isInList(entry.getKey(), itemIds)).forEach(entry -> channelGroup.add(entry.getValue())); } return channelGroup; }
public static void shutdownChannelFactory( EventLoopGroup group, ExecutorService bossExecutor, ExecutorService workerExecutor, ChannelGroup allChannels) { // Close all channels if (allChannels != null) { closeChannels(allChannels); } // Shutdown the channel factory if (group != null) { group.shutdownGracefully(); } // Stop boss threads if (bossExecutor != null) { shutdownExecutor(bossExecutor, "bossExecutor"); } // Finally stop I/O workers if (workerExecutor != null) { shutdownExecutor(workerExecutor, "workerExecutor"); } // Release any other resources netty might be holding onto via this group if (group != null) { // TODO: Find netty4 equivalent (may not be nessisary with shutdown gracefully) // group.releaseExternalResources(); } }
public static void closeChannels(ChannelGroup allChannels) { if (allChannels.size() > 0) { // TODO : allow an option here to control if we need to drain connections and wait instead of // killing them all try { // log.info("Closing %s open client connections", allChannels.size()); if (!allChannels.close().await(5, TimeUnit.SECONDS)) { // log.warn("Failed to close all open client connections"); } } catch (InterruptedException e) { // log.warn("Interrupted while closing client connections"); Thread.currentThread().interrupt(); } } }