akka简单示例

刚刚开始接触akka,网上找了2个简单示例,并在公司运营机器上尝试,踩了一些坑,在此记录。

1. 本地hello world

 1 [[email protected] ~/akka_example/hello_world]$ cat src/helloWorld.scala
 2 package our.examples
 3 import akka.actor.Actor
 4 import akka.actor.ActorSystem
 5 import akka.actor.Props
 6
 7 class HelloActor extends Actor {
 8   def receive = {
 9     case "hello" => println("hello back at you")
10     case _       => println("huh?")
11   }
12 }
13
14 object HelloApp extends App {
15         override def main(args: Array[String]){
16                 val system = ActorSystem("HelloSystem")
17                         // default Actor constructor
18                         val helloActor = system.actorOf(Props[HelloActor], name = "helloactor")
19                         helloActor ! "hello"
20                         helloActor ! "buenos dias"
21         }
22 }
 1 [[email protected] ~/akka_example/hello_world]$ cat Makefile
 2 SRC_DIR := src
 3 SRC := $(shell find ${SRC_DIR} -name "*.scala")
 4 DIR=our
 5
 6 TARGET := HelloApp.jar
 7
 8 SCALAC := scalac
 9 SCFLAGS := /usr/local/scala-2.10.4/lib/akka-actors.jar
10
11 .PHONY: all clean
12
13 all: ${TARGET}
14
15 ${TARGET}: ${SRC}
16         ${SCALAC} -cp ${SCFLAGS} $^
17
18 clean:
19         ${RM} -r ${TARGET} ${DIR}
1 [[email protected] ~/akka_example/hello_world]$ cat run.sh
2 #!/bin/bash
3
4
5 java -cp 6  .:/usr/local/scala-2.10.4/lib/scala-library.jar:/usr/local/scala-2.10.4/lib/akka-actors.jar:/usr/local/scala-2.10.4/lib/typesafe-config.jar7   our.examples.HelloApp

执行结果:

[[email protected] ~/akka_example/hello_world]$ ./run.sh
hello back at you
huh?

2. 简单CS示例

server端:

 1 [[email protected] ~/akka_example/remote_service/server]$ cat src/HelloRemote.scala
 2 package remote
 3 import akka.actor.Actor
 4 import akka.actor.ActorSystem
 5 import akka.actor.Props
 6
 7 class RemoteActor extends Actor{
 8         def receive = {
 9                 case msg:String =>
10                         println(s"RemoteActor received message ‘$msg‘")
11                         sender ! "hello from RemoteActor"
12         }
13 }
14
15 object HelloRemote extends App{
16         val system = ActorSystem("HelloRemoteSystem")
17         val remoteActor = system.actorOf(Props[RemoteActor], name="RemoteActor")
18         remoteActor ! "The remote actor is alive"
19 }
 1 [[email protected] ~/akka_example/remote_service/server]$ cat application.conf
 2 akka {
 3   loglevel = "DEBUG"
 4   actor {
 5     provider = "akka.remote.RemoteActorRefProvider"
 6    }
 7    remote {
 8      transport = "akka.remote.netty.NettyRemoteTransport"
 9      //log-sent-messages = on
10      //log-received-messages = on
11      netty {
12        hostname = "127.0.0.1"
13        port = 5150
14      }
15    }
16 }
 1 [[email protected] ~/akka_example/remote_service/server]$ cat Makefile
 2 SRC_DIR := src
 3 SRC := $(shell find ${SRC_DIR} -name "*.scala")
 4 DIR=remote
 5
 6 TARGET := HelloRemote.jar
 7
 8 SCALAC := scalac
 9 SCFLAGS := /usr/local/scala-2.10.4/lib/akka-actors.jar
10
11 .PHONY: all clean
12
13 all: ${TARGET}
14
15 ${TARGET}: ${SRC}
16         ${SCALAC} -cp ${SCFLAGS} $^
17
18 clean:
19         ${RM} -r ${TARGET} ${DIR}
1 [[email protected] ~/akka_example/remote_service/server]$ cat run.sh
2 #!/bin/bash
3
4 AKKA_LIB_PATH="/usr/local/akka-2.1.4/lib/akka/"
5
6 java -cp 7  .:/usr/local/scala-2.10.4/lib/scala-library.jar:/usr/local/scala-2.10.4/lib/akka-actors.jar:/usr/local/scala-2.10.4/lib/typesafe-config.jar:${AKKA_LIB_PATH}/akka-remote_2.10-2.1.4.jar:${AKKA_LIB_PATH}/protobuf-java-2.4.1.jar:${AKKA_LIB_PATH}/netty-3.5.8.Final.jar 8  remote.HelloRemote

client端:

 1 [[email protected] ~/akka_example/remote_service/client]$ cat src/HelloLocal.scala
 2 package client
 3 import akka.actor._
 4
 5 object HelloLocal extends App{
 6         implicit val system = ActorSystem("LocalSystem")
 7         val localActor = system.actorOf(Props[LocalActor], name="LocalActor")
 8         localActor ! "START"
 9 }
10
11 class LocalActor extends Actor{
12         val remote = context.actorFor("akka://[email protected]:5150/user/RemoteActor")
13         var counter = 0
14         def receive = {
15                 case "START" =>
16                         remote ! "HELLO from the LocalActor"
17                 case msg:String =>
18                         println(s"LocalActor received message: ‘$msg‘")
19                         if(counter < 5){
20                                 sender ! "hello back to you"
21                                 counter += 1
22                         }
23         }
24 }
 1 [[email protected] ~/akka_example/remote_service/client]$ cat application.conf
 2 akka {
 3   //loglevel = "DEBUG"
 4   actor {
 5     provider = "akka.remote.RemoteActorRefProvider"
 6   }
 7   remote {
 8     transport = "akka.remote.netty.NettyRemoteTransport"
 9     //log-sent-messages = on
10     //log-received-messages = on
11     netty {
12       hostname = "127.0.0.1"
13       port = 0
14     }
15   }
16 }
 1 [[email protected] ~/akka_example/remote_service/client]$ cat Makefile
 2 SRC_DIR := src
 3 SRC := $(shell find ${SRC_DIR} -name "*.scala")
 4 DIR=client
 5
 6 TARGET := HelloLocal.jar
 7
 8 SCALAC := scalac
 9 SCFLAGS := /usr/local/scala-2.10.4/lib/akka-actors.jar
10
11 .PHONY: all clean
12
13 all: ${TARGET}
14
15 ${TARGET}: ${SRC}
16         ${SCALAC} -cp ${SCFLAGS} $^
17
18 clean:
19         ${RM} -r ${TARGET} ${DIR}
1 [[email protected] ~/akka_example/remote_service/client]$ cat run.sh
2 #!/bin/bash
3
4 AKKA_LIB_PATH="/usr/local/akka-2.1.4/lib/akka/"
5
6 java -cp 7  .:/usr/local/scala-2.10.4/lib/scala-library.jar:/usr/local/scala-2.10.4/lib/akka-actors.jar:/usr/local/scala-2.10.4/lib/typesafe-config.jar:${AKKA_LIB_PATH}/akka-remote_2.10-2.1.4.jar:${AKKA_LIB_PATH}/protobuf-java-2.4.1.jar:${AKKA_LIB_PATH}/netty-3.5.8.Final.jar 8  client.HelloLocal

执行结果:

[[email protected] /data/torstan/akka_example/remote_service/server]# ./run.sh
[DEBUG] [12/10/2014 17:31:57.074] [main] [EventStream(akka://HelloRemoteSystem)] logger log1-Logging$DefaultLogger started
[DEBUG] [12/10/2014 17:31:57.080] [main] [EventStream(akka://HelloRemoteSystem)] Default Loggers started
[INFO] [12/10/2014 17:31:57.269] [main] [NettyRemoteTransport(akka://[email protected]:5150)] [email protected]://[email protected]:5150
RemoteActor received message ‘The remote actor is alive‘
[INFO] [12/10/2014 17:32:01.768] [HelloRemoteSystem-10] [NettyRemoteTransport(akka://[email protected]:5150)] [email protected]://[email protected]:48437
[DEBUG] [12/10/2014 17:32:01.769] [HelloRemoteSystem-10] [RemoteClient(akka://HelloRemoteSystem)] Starting remote client connection to [akka://[email protected]:48437]
[DEBUG] [12/10/2014 17:32:01.771] [HelloRemoteSystem-10] [NettyRemoteTransport(akka://[email protected]:5150)] [email protected]://[email protected]:5150: Client[akka://[email protected]:48437]
RemoteActor received message ‘HELLO from the LocalActor‘
[DEBUG] [12/10/2014 17:32:01.782] [HelloRemoteSystem-akka.actor.default-dispatcher-2] [akka.serialization.Serialization(akka://HelloRemoteSystem)] Using serializer[akka.serialization.JavaSerializer] for message [java.lang.String]
RemoteActor received message ‘hello back to you‘
RemoteActor received message ‘hello back to you‘
RemoteActor received message ‘hello back to you‘
RemoteActor received message ‘hello back to you‘
RemoteActor received message ‘hello back to you‘

[[email protected] ~/akka_example/remote_service/client]$ ./run.sh
[INFO] [12/10/2014 17:32:01.668] [main] [NettyRemoteTransport(akka://[email protected]:48437)] [email protected]://[email protected]:48437
[INFO] [12/10/2014 17:32:01.755] [LocalSystem-akka.actor.default-dispatcher-3] [NettyRemoteTransport(akka://[email protected]:48437)] [email protected]://[email protected]:5150
LocalActor received message: ‘hello from RemoteActor‘
LocalActor received message: ‘hello from RemoteActor‘
LocalActor received message: ‘hello from RemoteActor‘
LocalActor received message: ‘hello from RemoteActor‘
LocalActor received message: ‘hello from RemoteActor‘
LocalActor received message: ‘hello from RemoteActor‘

遇到的坑:

1. 运行时各种各样的依赖缺失

比如:

[[email protected] ~/akka_example/remote_service/client]$ ./run.sh 
Exception in thread "main" java.lang.ClassNotFoundException: akka.remote.RemoteActorRefProvider
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:270)
at akka.actor.ReflectiveDynamicAccess$$anonfun$getClassFor$1.apply(DynamicAccess.scala:68)
at akka.actor.ReflectiveDynamicAccess$$anonfun$getClassFor$1.apply(DynamicAccess.scala:67)
at scala.util.Try$.apply(Try.scala:161)

google到答案是没有加载依赖文件akka-remote.jar,后来发现是没有安装akka。

2. Exception in thread "main" java.lang.NoSuchMethodException: akka.remote.RemoteActorRefProvider.<init>(java.lang.String, akka.actor.ActorSystem$Settings, akka.event.EventStream, akka.actor.Scheduler, akka.actor.DynamicAccess

google到答案:

12 maj 2014 kl. 22:55 skrev Liang Tang <[email protected]>:

- show quoted text -

Yes, Scala 2.10 comes with Akka 2.1.0, which is not binary compatible with Akka 2.3.2. I recommend using sbt to resolve the dependencies instead of manually constructing a command line, i.e. using the runMain task.

Regards,

Roland

https://groups.google.com/forum/#!topic/akka-user/zibfABh4cs8

因为安装的scala版本scala-2.10.4与akka的版本akka-2.2.4不兼容,scala-2.10.4应该与akka-2.1.4配套使用。

参考文献:

http://alvinalexander.com/scala/simple-scala-akka-actor-examples-hello-world-actors

http://alvinalexander.com/scala/simple-akka-actors-remote-example

时间: 2024-08-06 15:56:23

akka简单示例的相关文章

akka简单示例-2

手动敲了一遍计算pi的示例:http://www.gtan.com/akka_doc/intro/getting-started-first-scala.html 有个笔误,花了半个小时定位. 1 [[email protected] ~/akka_example/pi]$ cat src/Pi.scala 2 package akka.tutorial.first.scala 3 import akka.actor._ 4 import akka.routing.RoundRobinRoute

AKKA HTTP 简单示例

AKKA HTTP 简单示例 依赖包: compile("com.typesafe.akka:akka-http_2.13:10.1.8") compile("com.typesafe.akka:akka-stream_2.13:2.5.23") 代码示例: package http import akka.actor.ActorSystem import akka.http.javadsl.server.HttpApp import akka.http.javad

AMQP消息队列之RabbitMQ简单示例

前面一篇文章讲了如何快速搭建一个ActiveMQ的示例程序,ActiveMQ是JMS的实现,那这篇文章就再看下另外一种消息队列AMQP的代表实现RabbitMQ的简单示例吧.在具体讲解之前,先通过一个图来概览下: 1.添加Maven依赖 <!-- rabbitmq begin --> <dependency> <groupId>org.springframework.amqp</groupId> <artifactId>spring-rabbit

HMM的维特比算法简单示例

今天读了一位大牛的关于HMM的技术博客,读完之后,写了一个关于维特比算法的简单示例,用scala和java语言混合编写的.现在上传之. package com.txq.hmm import java.utilimport scala.collection._ /** * HMM维特比算法,根据显示状态链条估计隐式链条 * @param states 隐式states * @param observations 显式states * @param start_probability 初始概率向量

spring-servlet.xml简单示例

spring-servlet.xml简单示例 某个项目中的spring-servlet.xml 记下来以后研究用 1 <!-- springMVC简单配置 --> 2 <?xml version="1.0" encoding="UTF-8"?> 3 <beans xmlns="http://www.springframework.org/schema/beans" 4 xmlns:xsi="http://w

关于Ajax实现的简单示例

一.代码示例 关于Ajax的基本概念(包括XMLHttpRequest对象及其相关方法属性)移步这里(w3school中文版)学习了解. <!doctype html> <html lang = "en"> <head> <meta charset = "utf-8"> <title>使用Ajax异步加载数据</title> <script type = "text/javasc

【转】bind简单示例

bind简单示例代码 namespace { class placeholder_ {}; placeholder_ __1; } template <typename R, typename T, typename Arg> class simple_bind_t { private: typedef R (T::*F)(Arg); F f_; T* t_; Arg& a_; public: simple_bind_t(F f, T* t, Arg &a) : f_(f),

SQL左连接、右连接和内连接的简单示例

left join(左联接) 返回包括左表中的所有记录和右表中联结字段相等的记录: right join(右联接) 返回包括右表中的所有记录和左表中联结字段相等的记录: inner join(等值连接) 只返回两个表中联结字段相等的行:举例如下: -------------------------------------------- 表A记录如下: aID aNum 1 a20050111 2 a20050112 3 a20050113 4 a20050114 5 a20050115 表B记录

Backbone简单示例

要的资源: <script type="text/javascript" src="../dep/underscore-1.6.0.min.js"></script> <script type="text/javascript" src="../dep/jquery-1.11.1.min.js"></script> <script type="text/javas