如何修复导致 Netty 4 中的 IllegalArgumentException 的 AttributeKey

How to fix AttributeKey leading to IllegalArgumentException in Netty 4

我正在将 Netty 3 应用程序移植到 Netty 4。Netty 3 应用程序使用 Attachement 将对象附加到上下文。

正在阅读 New and noteworthy in 4.0 我看到附件已被删除并替换为 AttributeKey/AttributeMap。

问题是当我 运行 应用程序时这有效,但在集成测试下,我收到错误:

Caused by: java.lang.IllegalArgumentException: 'attr_key' is already in use

其中 attr_key 在可共享处理程序中定义如下:

private final AttributeKey<Object> ATTR_KEY = AttributeKey.newInstance("attr_key");

然后在同一个处理程序的其他地方使用 class 如下:

channel.attr(ATTR_KEY).set(new Object())

关于使用 AttributeKey/AttributeMap 防止此错误的推荐方法有任何想法或想法吗?谢谢!

使用属性键时,确保只构建 1 次。

这意味着,您需要将它们存储在private static final 变量中,private final 变量不够好,因为在多次构造class 时会出错。

如果无法确保方法newInstance方法被调用一次,则需要使用AttributeKey.valueOf,因此关闭了冲突检测。这是一些单元测试框架所必需的,其中库加载 1 次,但应用程序代码动态重新启动。