跳到主要内容

元信息-附加信息

介绍

在处理 action 时,通过 FlowContext 可以方便得到当前 userId。

如果开发者想在处理 action 时,携带上一些自定义的信息,可以通过元附加信息特性来完成。 将一些自定义信息保存到元附加信息后,之后的每个 action 请求可以通过 FlowContext 来得到这些自定义信息。

比如保存当前玩家的英雄角色信息、玩家昵称,又或者是你的项目的 userId 是 string 或其他类型则可以通过元信息这一特性来兼容。 简单的说,就是你想在 FlowContext 中获取一些玩家特有的信息数据时,可以通过这个特性来实现。

Example Source Code

see https://github.com/iohao/ionet-examples

path : ionet-cookbook-code

  • AttachmentAction

如何使用

自定义元信息类

@ProtobufClass
public class MyAttachment {
public long userId;
public String nickname;
}

更新元信息

  • code 10~11,设置并同步更新元信息。
  • code 20,获取元信息。
@ActionController(AttachmentCmd.cmd)
public class AttachmentAction {
@ActionMethod(AttachmentCmd.updateAttachment)
private boolean updateAttachment(MyFlowContext flowContext) {
var attachment = new MyAttachment();
attachment.userId = flowContext.getUserId();
attachment.nickname = "Michael Jackson";

// set and update attachment
flowContext.setAttachment(attachment);
flowContext.updateAttachment();
// Async update
// flowContext.updateAttachmentAsync();

return true;
}

@ActionMethod(AttachmentCmd.printAttachment)
private String printAttachment(FlowContext flowContext) {
MyAttachment attachment = flowContext.getAttachment();
return attachment.toString();
}
}

配合自定义 FlowContext

我们可以配合自定义 FlowContext 特性 ,做一些更符合定制的扩展,如下。

  • code 5,调用 MyFlowContext.getNickname() 方法
  • code 10,自定义 MyFlowContext,我们可以在该类中添加任意的便捷方法。
@ActionController(1)
public class DemoAction {
@ActionMethod(1)
public String getNickname(MyFlowContext flowContext) {
return flowContext.getNickname();
}
}

@Setter
public class MyFlowContext extends DefaultFlowContext {
MyAttachment attachment;

@Override
public MyAttachment getAttachment() {
if (Objects.isNull(this.attachment)) {
this.attachment = this.getAttachment(MyAttachment.class);
}

return this.attachment;
}

public String getNickname() {
MyAttachment attachment = this.getAttachment();
return attachment.nickname;
}
}