本文整理匯總了Java中io.netty.channel.group.ChannelGroup類的典型用法代碼示例。如果您正苦於以下問題:Java ChannelGroup類的具體用法?Java ChannelGroup怎麽用?Java ChannelGroup使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
ChannelGroup類屬於io.netty.channel.group包,在下文中一共展示了ChannelGroup類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: closeConnectionAsync
import io.netty.channel.group.ChannelGroup; //導入依賴的package包/類
@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;
}
}
示例2: WhirlpoolMessageHandler
import io.netty.channel.group.ChannelGroup; //導入依賴的package包/類
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);
}
示例3: sendReq
import io.netty.channel.group.ChannelGroup; //導入依賴的package包/類
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);
}
}
示例4: chat
import io.netty.channel.group.ChannelGroup; //導入依賴的package包/類
@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;
}
示例5: initChannel_adds_OpenChannelLimitHandler_after_RequestInfoSetterHandler_and_uses_cached_ChannelGroup
import io.netty.channel.group.ChannelGroup; //導入依賴的package包/類
@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));
}
示例6: channelActive
import io.netty.channel.group.ChannelGroup; //導入依賴的package包/類
@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);
}
示例7: sendToGroup
import io.netty.channel.group.ChannelGroup; //導入依賴的package包/類
/**
* 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);
}
});
}
示例8: sendToGroup
import io.netty.channel.group.ChannelGroup; //導入依賴的package包/類
/**
* 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);
}
示例9: NettyServer
import io.netty.channel.group.ChannelGroup; //導入依賴的package包/類
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();
}
示例10: makeMessageInfoToDevice
import io.netty.channel.group.ChannelGroup; //導入依賴的package包/類
/**
* 實際發送消息方法
*
* @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;
}
示例11: testMasterSlaveSentinelConnectionCount
import io.netty.channel.group.ChannelGroup; //導入依賴的package包/類
@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();
}
示例12: testMasterSlaveSentinelClosesSentinelConnections
import io.netty.channel.group.ChannelGroup; //導入依賴的package包/類
@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);
}
示例13: MetricBatcher
import io.netty.channel.group.ChannelGroup; //導入依賴的package包/類
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
}
}
示例14: closeChannelGroup
import io.netty.channel.group.ChannelGroup; //導入依賴的package包/類
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[] {}));
}
}
示例15: RedisChannelInitializer
import io.netty.channel.group.ChannelGroup; //導入依賴的package包/類
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;
}