本文整理汇总了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;
}