akka java api helloworld

本文介绍了一个使用Akka框架的简单Actor模型示例。示例中,Actor A创建了子Actor B,并向其发送消息;Actor B接收到消息后回复确认信息。此过程展示了Actor之间的基本通信机制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.usoft;
 
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.Props;
import akka.actor.UntypedActor;
 
/**
 * Created by liyanxin on 2015/1/8.
 */
public class HelloWorld {
 
    /**
     * 在这里实现这样一个功能,A actor给 B actor 发送消息,接收后返回消息说已收到
     */
    public static class extends UntypedActor {
        @Override
        public void preStart() throws Exception {
 
            // 使用当前actor的context 创建了一个子actor,B actor就是A actor的子actor
            // using an actor’s context will create a child actor
            final ActorRef child =
                    getContext().actorOf(Props.create(B.class), "myChild");
            child.tell("good moring"this.getSelf());
        }
 
        @Override
        public void onReceive(Object message) throws Exception {
            if (message instanceof String) {
                System.out.println("接收到B Actor的消息:" + message);
                getContext().stop(getSelf());
            }
        }
    }
 
    public static class extends UntypedActor {
        @Override
        public void onReceive(Object message) throws Exception {
            if (message instanceof String) {
                System.out.println("接收到A Actor的消息:" + message);
                this.getSender().tell("thank you!"this.getSelf());
            }
        }
    }
 
 
    public static void main(String args[]) {
 
        ActorSystem system = ActorSystem.create("myActorSystem");
 
        // Actors are created by passing a Props instance into the actorOf factory method which is available on
        // ActorSystem and ActorContext.
        // 通过ActorSystem 和 ActorContext的工场方法actorOf创建actor
        // 工场方法需要接收一个Props instance
        system.actorOf(Props.create(A.class), "helloWorld");
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值