Akka Java有限状态机示例

siv3szwd  于 2022-11-05  发布在  Java
关注(0)|答案(3)|浏览(174)

**请注意:**我是一名Java开发人员,对Scala没有任何实际应用知识(遗憾的是)。我希望答案中提供的任何代码示例都使用Akka的Java API。

我尝试使用Akka FSM API来建模下面的超简单状态机。实际上,我的机器要复杂得多,但是这个问题的答案将允许我推断出我的实际FSM。

所以我有两个状态:OffOn。您可以通过调用SomeObject#powerOn(<someArguments>)打开计算机的电源来从Off -> On切换到On -> Off。您可以通过调用SomeObject#powerOff(<someArguments>)关闭计算机的电源来从On -> Off切换到SomeObject#powerOff(<someArguments>)
我想知道我需要什么参与者和支持类来实现这个FSM。我 * 相信 * 代表FSM的参与者必须扩展AbstractFSM。但是什么类代表这两种状态?什么代码公开和实现powerOn(...)powerOff(...)状态转换?一个工作的Java示例,甚至仅仅是Java伪代码,在这里对我来说都有很大帮助。

xt0899hw

xt0899hw1#

我认为我们可以做得比来自FSM docs(http://doc.akka.io/docs/akka/snapshot/java/lambda-fsm.html)的copypasta更好一些。
您有两个触发器(或事件,或信号)-- powerOn和powerOff。您希望将这些信号发送给一个Actor并使其改变状态,其中两个有意义的状态是On和Off。
现在,严格地说,FSM还需要一个组件:您希望在过渡时采取的操作。

FSM:
State (S) x Event (E) -> Action (A), State (S')

Read: "When in state S, if signal E is received, produce action A and advance to state S'"

你不需要一个动作,但是一个Actor不能被直接检查,也不能被直接修改。所有的变异和确认都是通过异步消息传递发生的。
在你的例子中,转换时没有提供任何操作,你的状态机基本上是无操作的。操作发生,状态转换没有副作用,状态是不可见的,所以一个工作的机器和一个坏的机器是一样的。由于这一切都是异步发生的,你甚至不知道坏的东西什么时候完成。
因此,请允许我稍微扩展一下您的合同,并在FSM定义中包括以下操作:

When in Off, if powerOn is received, advance state to On and respond to the caller with the new state
 When in On, if powerOff is received, advance state to Off and respond to the caller with the new state

现在,我们也许能够构建一个实际上可测试的FSM。
让我们为您的两个信号定义一对类。(AbstractFSM DSL期望在类上匹配):

public static class PowerOn {}
public static class PowerOff {}

让我们为您的两个状态定义一对枚举:

enum LightswitchState { on, off }

让我们定义一个AbstractFSM Actor(http://doc.akka.io/japi/akka/2.3.8/akka/actor/AbstractFSM.html)。通过扩展AbstractFSM,我们可以使用与上面类似的FSM定义链来定义一个Actor,而不是直接在onReceive()方法中定义消息行为。它为这些定义提供了一个很好的DSL,并且(有点奇怪的是)期望在静态初始化器中设置这些定义。
不过,我们还是要绕个圈子:AbstractFSM定义了两个泛型,用于提供编译时类型检查。
S是我们希望使用的State类型的基,D是Data类型的基。(可能是电灯开关的功率表?),您将构建一个单独的类来保存这些数据,而不是尝试向AbstractFSM的子类添加新成员。由于我们没有数据,让我们定义一个伪类,这样您就可以看到它是如何传递的:

public static class NoDataItsJustALightswitch {}

这样,我们就可以创建演员类了。

public class Lightswitch extends AbstractFSM<LightswitchState, NoDataItsJustALightswitch> {
    {  //static initializer
        startWith(off, new NoDataItsJustALightswitch()); //okay, we're saying that when a new Lightswitch is born, it'll be in the off state and have a new NoDataItsJustALightswitch() object as data

        //our first FSM definition
        when(off,                                //when in off,
            matchEvent(PowerOn.class,            //if we receive a PowerOn message,
                NoDataItsJustALightswitch.class, //and have data of this type,
                (powerOn, noData) ->             //we'll handle it using this function:
                    goTo(on)                     //go to the on state,
                        .replying(on);           //and reply to the sender that we went to the on state
            )
        );

        //our second FSM definition
        when(on, 
            matchEvent(PowerOff.class, 
                NoDataItsJustALightswitch.class, 
                (powerOn, noData) -> {
                    goTo(off)
                        .replying(off);
                    //here you could use multiline functions,
                    //and use the contents of the event (powerOn) or data (noData) to make decisions, alter content of the state, etc.
                }
            )
        );

        initialize(); //boilerplate
    }
}

我肯定你在想:我该如何使用它呢?!让我们使用直接的JUnit和Akka Testkit for java来创建一个测试工具:

public class LightswitchTest { 
    @Test public void testLightswitch() {
        ActorSystem system = ActorSystem.create("lightswitchtest");//should make this static if you're going to test a lot of things, actor systems are a bit expensive
        new JavaTestKit(system) {{ //there's that static initializer again
            ActorRef lightswitch = system.actorOf(Props.create(Lightswitch.class)); //here is our lightswitch. It's an actor ref, a reference to an actor that will be created on 
                                                                                    //our behalf of type Lightswitch. We can't, as mentioned earlier, actually touch the instance 
                                                                                    //of Lightswitch, but we can send messages to it via this reference.

            lightswitch.tell(    //using the reference to our actor, tell it
                new PowerOn(),   //to "Power On," using our message type
                getRef());       //and giving it an actor to call back (in this case, the JavaTestKit itself)

            //because it is asynchronous, the tell will return immediately. Somewhere off in the distance, on another thread, our lightbulb is receiving its message

            expectMsgEquals(LightswitchState.on);   //we block until the lightbulb sends us back a message with its current state ("on.")
                                                     //If our actor is broken, this call will timeout and fail.

            lightswitch.tell(new PowerOff(), getRef());

            expectMsgEquals(LightswitchState.off);   

            system.stop(lightswitch); //switch works, kill the instance, leave the system up for further use
        }};
    }
}

这就是你:一个FSM lightswitch。不过老实说,这样一个小例子并不能真正展示FSM的强大功能,因为一个无数据的例子可以作为一组“变成/不变成”行为来执行,所用的LoC只有一半,没有泛型或lambda。IMO的可读性更强。
PS考虑学习Scala,如果仅仅是为了能够阅读其他人的代码的话!Atomic Scala这本书的前半部分可以在网上免费获得。
PPS如果你真的想要一个可组合的状态机,我维护Pulleys,一个基于纯java的状态图的状态机引擎。它已经发展了很多年了(大量的XML和旧模式,没有DI集成),但是如果你真的想把状态机的实现从输入和输出中分离出来,可能会有一些灵感。

u59ebvdq

u59ebvdq2#

我知道Scala的演员。
此Java起始代码可以帮助您继续:
是的,从AbstractFSM扩展您的SimpleFSM
州是AbstractFSM中的enum
您的<someArguments>可以是您的AbstractFSM中的Data部件
您的powerOnpowerOff是参与者消息/事件。状态切换在转换部分

// states
enum State {
  Off, On
}

enum Uninitialized implements Data {
  Uninitialized
}

public class SimpleFSM extends AbstractFSM<State, Data> {
    {
        // fsm body
        startWith(Off, Uninitialized);

        // transitions
        when(Off,
            matchEvent(... .class ...,
            (... Variable Names ...) ->
              goTo(On).using(...) ); // powerOn(<someArguments>)

        when(On,
            matchEvent(... .class ...,
            (... Variable Names ...) ->
              goTo(Off).using(...) ); // powerOff(<someArguments>)

        initialize();

    }
}

真实的工作项目见
Scala and Java 8 with Lambda Template for a Akka AbstractFSM

hpxqektj

hpxqektj3#

这是一个非常古老的问题,但如果你从Google获得了一个热门,但如果你仍然有兴趣用Akka实现FSM,我建议看看documentation的这一部分。
如果你想看看一个实用的模型驱动状态机是如何实现的,你可以查看我的blog1blog2

相关问题