Netty,并发writeAndFlush [英] Netty, concurrent writeAndFlush

查看:155
本文介绍了Netty,并发writeAndFlush的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我们有某种发布/订阅协议.当有人进行连接和订阅时,我们可以将频道保存在Map,List或ChannelGroup中:

Lets say we have some kind of pub/sub protocol. When someone is connecting and subscribing, we can save channel in Map, List or ChannelGroup:

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    super.channelActive(ctx);
    log.debug("Client connected: {}", ctx.channel().remoteAddress());
    clients.add(ctx);
}

之后,当有消息或事件发生时,我可以通知客户:

After that, when some message has come or some event has happened, I can notify clients:

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    log.debug("Client {} published msg: {}", ctx.channel().remoteAddress(), msg);
    clients.foreach(client -> client.getChannel().writeAndFlush(msg));
}

因此,让我们想象一下某些客户端同时发布消息(例如"msg1","abc2")的情况.是否会导致并发问题?例如,在某些情况下我可以检索"msabg1c2"而不是"msg1abc2"吗?还是Netty负责此类案件?

So lets imagine situation when some clients are publishing messages (e.g. "msg1", "abc2") in the same moment. Does it lead to concurrent problems? For example can I retrieve in some cases "msabg1c2" instead of "msg1abc2"? Or Netty takes care of such cases?

推荐答案

频道是线程安全的,因此只要调用顺序正确,就不会出现任何问题

Channel is thread-safe so no you should not have any problems as long as the calling order is correct

这篇关于Netty,并发writeAndFlush的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆