Stash
依赖
为了使用 Akka Actor 类型,你需要将以下依赖添加到你的项目中:
1. <!-- Maven -->
2. <dependency>
3. <groupId>com.typesafe.akka</groupId>
4. <artifactId>akka-actor-typed_2.12</artifactId>
5. <version>2.5.23</version>
6. </dependency>
8. <!-- Gradle -->
9. dependencies {
10. compile group: 'com.typesafe.akka', name: 'akka-actor-typed_2.12', version: '2.5.23'
11. }
13. <!-- sbt -->
14. libraryDependencies += "com.typesafe.akka" %% "akka-actor-typed" % "2.5.23"
简介
Stash使 Actor 能够临时缓冲所有或某些不能或不应该使用 Actor 当前行为处理的消息。
当这一点很有用,一个典型的例子是,如果 Actor 在接受第一条真实消息之前加载了一些初始状态或者初始化了一些资源;另一个例子是,Actor 在处理下一条消息之前正在等待完成某件事情。
让我们用一个例子来说明这两个问题。它是一个 Actor,就像对存储在数据库中的值的单点访问一样使用。启动后,它从数据库中加载当前状态,并在等待该初始值的同时,所有传入的消息都被存储起来。
当一个新的状态保存在数据库中时,它也会存储传入的消息,以使处理连续进行,一个接一个,没有多个挂起的写入。
1. import akka.actor.typed.javadsl.StashBuffer;
3. interface DB {
4. CompletionStage<Done> save(String id, String value);
6. CompletionStage<String> load(String id);
7. }
9. public static class DataAccess {
11. static interface Command {}
13. public static class Save implements Command {
14. public final String payload;
15. public final ActorRef<Done> replyTo;
17. public Save(String payload, ActorRef<Done> replyTo) {
18. this.payload = payload;
19. this.replyTo = replyTo;
20. }
21. }
23. public static class Get implements Command {
24. public final ActorRef<String> replyTo;
26. public Get(ActorRef<String> replyTo) {
27. this.replyTo = replyTo;
28. }
29. }
31. static class InitialState implements Command {
32. public final String value;
34. InitialState(String value) {
35. this.value = value;
36. }
37. }
39. static class SaveSuccess implements Command {
40. public static final SaveSuccess instance = new SaveSuccess();
42. private SaveSuccess() {}
43. }
45. static class DBError implements Command {
46. public final RuntimeException cause;
48. public DBError(RuntimeException cause) {
49. this.cause = cause;
50. }
51. }
53. private final StashBuffer<Command> buffer = StashBuffer.create(100);
54. private final String id;
55. private final DB db;
57. public DataAccess(String id, DB db) {
58. this.id = id;
59. this.db = db;
60. }
62. Behavior<Command> behavior() {
63. return Behaviors.setup(
64. context -> {
65. context.pipeToSelf(
66. db.load(id),
67. (value, cause) -> {
68. if (cause == null) return new InitialState(value);
69. else return new DBError(asRuntimeException(cause));
70. });
72. return init();
73. });
74. }
76. private Behavior<Command> init() {
77. return Behaviors.receive(Command.class)
78. .onMessage(
79. InitialState.class,
80. (context, message) -> {
81. // now we are ready to handle stashed messages if any
82. return buffer.unstashAll(context, active(message.value));
83. })
84. .onMessage(
85. DBError.class,
86. (context, message) -> {
87. throw message.cause;
88. })
89. .onMessage(
90. Command.class,
91. (context, message) -> {
92. // stash all other messages for later processing
93. buffer.stash(message);
94. return Behaviors.same();
95. })
96. .build();
97. }
99. private Behavior<Command> active(String state) {
100. return Behaviors.receive(Command.class)
101. .onMessage(
102. Get.class,
103. (context, message) -> {
104. message.replyTo.tell(state);
105. return Behaviors.same();
106. })
107. .onMessage(
108. Save.class,
109. (context, message) -> {
110. context.pipeToSelf(
111. db.save(id, message.payload),
112. (value, cause) -> {
113. if (cause == null) return SaveSuccess.instance;
114. else return new DBError(asRuntimeException(cause));
115. });
116. return saving(message.payload, message.replyTo);
117. })
118. .build();
119. }
121. private Behavior<Command> saving(String state, ActorRef<Done> replyTo) {
122. return Behaviors.receive(Command.class)
123. .onMessageEquals(
124. SaveSuccess.instance,
125. context -> {
126. replyTo.tell(Done.getInstance());
127. return buffer.unstashAll(context, active(state));
128. })
129. .onMessage(
130. DBError.class,
131. (context, message) -> {
132. throw message.cause;
133. })
134. .onMessage(
135. Command.class,
136. (context, message) -> {
137. buffer.stash(message);
138. return Behaviors.same();
139. })
140. .build();
141. }
143. private static RuntimeException asRuntimeException(Throwable t) {
144. // can't throw Throwable in lambdas
145. if (t instanceof RuntimeException) {
146. return (RuntimeException) t;
147. } else {
148. return new RuntimeException(t);
149. }
150. }
151. }
需要注意的一件重要的事情是,StashBuffer是一个缓冲区,存储的消息将保存在内存中,直到它们被取消显示(或者 Actor 被停止并被垃圾回收)。建议避免存储过多的消息,以避免过多的内存使用,如果许多 Actor 存储过多的消息,甚至会有OutOfMemoryError的风险。因此,StashBuffer是有界的,在创建时必须指定它可以保存多少消息的capacity。
如果你试图存储的消息超过了capacity的容量,那么将抛出一个StashOverflowException。你可以在存储消息之前使用StashBuffer.isFull,以避免出现这种情况并采取其他操作,例如删除消息。
当通过调用unstashAll取消缓冲消息的显示时,所有消息将按添加它们的顺序依次处理,并且除非引发异常,否则将全部处理。在unstashAll完成之前,Actor 对其他新消息没有响应。这也是保持隐藏信息数量低的另一个原因。占用消息处理线程太长时间的 Actor 可能会导致其他 Actor 发生饥饿现象。
这可以通过使用StashBuffer.unstash 的numberOfMessages参数来减轻消息负载,然后在继续取消更多的显示之前向context.getSelf发送一条消息。这意味着其他新消息可能会在这期间到达,并且必须将它们存储起来,以保持消息的原始顺序。不过这将使它变得更加复杂,所以最好将隐藏消息的数量保持在较低的水平。
英文原文链接:Stash.
