The ONE使用笔记:为消息添加新字段

数据包在The ONE叫消息Message,本文介绍如何为消息添加新字段。我之前的做法是直接在Message类上修改,读了SprayAndWaitRouter源码之后,才知道可以利用The ONE消息属性进行添加,这方法更加直观可控。

1. 概述

为消息添加新字段,涉及到的操作如下:

public static final String MSG_MY_PROPERTY = ;  //定义字段名称,假设为MSG_MY_PROPERTY

msg.addProperty(MSG_MY_PROPERTY, new Integer(initialValvue));     //添加字段,重写createNewMessage(Message msg)
Integer nrofCopies = (Integer)m.getProperty(MSG_MY_PROPERTY);     //读取
msg.updateProperty(MSG_MY_PROPERTY, value);                       //更新

2. 实例

为消息创建一个新的属性,重写createNewMessage,初始化该字段,相关源代码如下:

//MyRouter.java
public static final String EPIDEMICXOR_NS = "EpidemicXorRouter";
public static final String MSG_XOR_PROPERTY = EPIDEMICXOR_NS + "." + "isXor";

@Override
public boolean createNewMessage(Message msg) {
    makeRoomForNewMessage(msg.getSize());

    msg.setTtl(this.msgTtl);
    msg.addProperty(MSG_XOR_PROPERTY, false); //就添加这一行
    addToMessages(msg, true);
    return true;
}

上述的createNewMessage实际上是将ActiveRouterMessageRouter展开,并添加一行,源代码如下:

//ActiveRouter.java​
@Override
public boolean createNewMessage(Message m) {
    makeRoomForNewMessage(m.getSize());
    return super.createNewMessage(m);
}​

//MessageRouter.java
public boolean createNewMessage(Message m) {
    m.setTtl(this.msgTtl);
    addToMessages(m, true);
    return true;
}​
赞赏

微信赞赏支付宝赞赏

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

8 thoughts on “The ONE使用笔记:为消息添加新字段

  • 2016年03月14日 星期一 at 05:23上午
    Permalink

    这里给的例子,好像是直接添加消息的属性并初始化一个值。 如果现在只需要添加一个属性,并指定这个属性的类型,而不需要指定这个属性的值,该怎么办? 谢谢!

    Reply
    • 2016年03月14日 星期一 at 06:34上午
      Permalink

      我想的办法是先附一个默认值,如果有需要,以后再更新。

      Reply
    • 2016年03月14日 星期一 at 01:00下午
      Permalink

      给个空值不就完了?比如:msg.addProperty(MSG_MY_PROPERTY, new Integer());

      Reply
  • 2016年03月14日 星期一 at 06:43上午
    Permalink

    一个新的问题:我用这种addProperty的方法给消息添加新的字段dataName。 我自己也自定义了一个MyMessageGenerator, 继承自MessageEventGenerator. 我需要在MyMessageGenerator中利用到新的消息字段,比如定义一个dataNameList, 通过类似drawHostAddress( )的方法实现drawDataName( ), 即每次产生一个消息,都从dataNameList中随机选取一个dataName赋给消息的那个新字段。请问这个如何实现呢? 我看了MessageEventGenerator的源码,好像那里的创建消息跟public ExternalEvent nextEvent() 有关? 可是这么一来如何在MyMessageGenerator里使用这个新的字段呢?

    Reply
    • 2016年03月14日 星期一 at 05:44下午
      Permalink

      解决了 谢谢!

      Reply
  • 2016年03月11日 星期五 at 01:28上午
    Permalink

    请问如何读取和修改消息的某个字段呢? 就是说,消息到达了某个节点,该节点会在转发消息之前修改这个消息的某个字段。谢谢!

    Reply
    • 2016年03月11日 星期五 at 04:54上午
      Permalink

      Integer nrofCopies = (Integer)m.getProperty(MSG_MY_PROPERTY); //读取
      msg.updateProperty(MSG_MY_PROPERTY, value); //更新

      Reply
  • Pingback: The ONE使用笔记:目录 | Spark & Shine