Actor和AKKA的使用

2022-08-24 20:36:15 字數 3214 閱讀 9767

com.typesafe

ssl-config-akka_2.11

0.1.2

org.scala-lang

scala-library

$com.typesafe.akka

akka-slf4j_2.11

2.5.23

com.typesafe.akka

akka-actor_2.11

2.5.23

com.typesafe.akka

akka-stream_2.11

2.5.23

com.typesafe.akka

akka-remote_2.11

2.5.23

actor資訊傳遞
import scala.actors.

object actordm else

// 傳送物件

myactor1 ! new ac("ac name")

// 關閉執行緒

myactor1 ! "stop"

} case class ac(name: string) {}

class myactor extends actor

println(s"接收的資訊是: $str")

sender ! s"傳送的 $str 已收到!"

}// 接收 ac()物件

case ac(name) => println(s"ac name = $name")}}

}}}

接收的資訊是: this is one info!

接收的資訊是: this is two info!

傳送的 this is two info! 已收到!

接收的資訊是: this is three info

傳送的 this is three info 已收到!

ac name = ac name

接收的資訊是: stop

actor資訊互傳
def main(args: array[string]): unit = 

case class request(question: string) {}

case class response(answer: string) {}

// student執行緒, 傳入teacher

class student(teacher: teacher) extends actor }}

}class teacher extends actor }}

}

teacher answer is i am teacher this is my answer!
資訊傳送
import akka.actor.

class helloactor extends actor

}}object actordm else if(num == 3)

}/**

* 為了不讓while的執行速度在receive方法之上,我們可以讓他休眠0.1秒

*/thread.sleep(100)

}}}

資訊互動
import akka.actor.

// 傳入乙個 actorref 物件

class user1(val user2: actorref) extends actor

}}class user2 extends actor

}}// 建立 actorsystem的工廠,用來生產actorref物件!

private val actorsystem = actorsystem("local_actor")

// 建立user2 的actorref物件

private val user2 = actorsystem.actorof(props[user2], "user2")

// props(new user1(user2)) 來建立需要傳參的user1類

private val user1 = actorsystem.actorof(props(new user1(user2)), "user1")

// 傳送開始訊號

user1 ! "開始"

}

服務端和客戶端互動程式

message.scala

case class servermessage(str: string) {}

case class clientmessage(msg: any) {}

serverakka.scala

import akka.actor.

import com.typesafe.config.

// 繼承 akka 的trait actor

class serverakka extends actor

println(s"來自客戶端的資訊是: " + msg)

// 返回資訊響應客戶端

sender ! servermessage(s"你傳送的 [ $msg ] 資訊伺服器已收到!")

}case _ => println("other info!")

}}object serverakka

}

clientakka.scala

import akka.actor.

import com.typesafe.config.configfactory

import scala.io.stdin

class clientakka extends actor

override def receive: receive =

// 接收客戶端的資訊

case clientmessage(msg) =>

}}object clientakka else

}}}

定時任務
package akka

import akka.actor.

import scala.util.random

case class task()

class timingtask extends actor

case task =>

}}object timingtask

}

akka 介紹 Actor 基礎

actors actors 是乙個非常輕的併發例項,基於事件驅動的非同步資訊處理.模式匹配是actor處理資訊的手段。它是對併發 鎖 分布系統的高度抽象。你只需要關注工作流。例子 package akka.io import akka.actor.actorlogging import akka.a...

Akka學習筆記(3) Actor

actor是akka中的核心概念,它為併發和分布式提供了一種更高階別的抽象,使併發程式設計更加容易。定義actor 定義乙個actor非常簡單 繼承actor,並提供receive方法即可。不帶構造引數的actor class myactor1 extends actor 帶構造引數的actor c...

Akka學習筆記05 Actor的建立

顯而易見,是通過actorof 方法建立乙個actor,但有兩種途徑 運用actor system。如 val system actorsystem myactorsystem val myactor system.actorof props new myactor 10 name myactor ...