akka-1 建立akka连接,并进行简单消息发送

1、配置mvn的pom 

    <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <encoding>UTF-8</encoding>
        <scala.version>2.11.12</scala.version>
        <scala.compat.version>2.11</scala.compat.version>
        <akka.version>2.4.17</akka.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.scala-lang</groupId>
            <artifactId>scala-library</artifactId>
            <version>${scala.version}</version>
        </dependency>
        <!--单机的actor通信-->
        <dependency>
            <groupId>com.typesafe.akka</groupId>
            <artifactId>akka-actor_2.11</artifactId>
            <version>${akka.version}</version>
        </dependency>
        <!--远程的actor通信- -->
        <dependency>
            <groupId>com.typesafe.akka</groupId>
            <artifactId>akka-remote_2.11</artifactId>
            <version>${akka.version}</version>
        </dependency>
    </dependencies>

    <!--编译插件-->
    <build>
        <pluginManagement>
            <plugins>
                <!--scala编译插件-->
                <plugin>
                    <groupId>net.alchim31.maven</groupId>
                    <artifactId>scala-maven-plugin</artifactId>
                </plugin>
                <!-- 编译java的插件 -->
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.5.1</version>
                </plugin>
            </plugins>
        </pluginManagement>
        <plugins>
            <plugin>
                <groupId>net.alchim31.maven</groupId>
                <artifactId>scala-maven-plugin</artifactId>
                <version>3.2.2</version>
                <executions>
                    <execution>
                        <id>scala-compile-first</id>
                        <phase>process-resources</phase>
                        <goals>
                            <goal>add-source</goal>
                            <goal>compile</goal>
                        </goals>
                    </execution>
                    <execution>
                        <id>scala-test-compile</id>
                        <phase>process-test-resources</phase>
                        <goals>
                            <goal>testCompile</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.5.1</version>
                <executions>
                    <execution>

                        <phase>compile</phase>
                        <goals>
                            <goal>compile</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

            <!--打jar插件-->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>3.2.0</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <filters>
                                <filter>
                                    <artifact>*:*</artifact>
                                    <excludes>
                                        <exclude>META-INF/*.SF</exclude>
                                        <exclude>META-INF/*.DSA</exclude>
                                        <exclude>META-INF/*.RSA</exclude>
                                    </excludes>
                                </filter>
                            </filters>

                            <transformers>
                                <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                    <resource>reference.conf</resource>
                                </transformer>
                            </transformers>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

2、Master消息发送(自己发自己)


import akka.actor.{Actor, ActorSystem, Props}
import com.typesafe.config.ConfigFactory

/**
 * 以后要使用actor编程模型进行通信,要跟akka发生关联
 */
class Master extends Actor{
  def receive:Receive={
    case "hello" => println("receive a Hello msg!")
    case "hello2" => println("你要干什么")
  }
}

object Master{
  //入口
  def main(args: Array[String]): Unit = {
    val host = "localhost"
    val port = 8888
    val configStr =
      s"""
        |akka.actor.provider="akka.remote.RemoteActorRefProvider"
        |akka.remote.netty.tcp.hostname="$host"
        |akka.remote.netty.tcp.port="$port"
       """.stripMargin
    val conf = ConfigFactory.parseString(configStr)
    //首先创建一个ActorSystem单例的,在scala中就是一个object
    val actorSystem = ActorSystem("MASTER_ACTOR_SYSTEM", conf)
    //通过ActorSystem创建Actor,通过反射创建Actor的实例
    val masteractor = actorSystem.actorOf(Props[Master], "MASTER_ACTOR")
    //向Actor发送消息
    masteractor!"hello2"
  }
}

3、Worker消息发送(自己发自己)


import akka.actor.{Actor, ActorSystem, Props}
import com.typesafe.config.ConfigFactory

class Worker extends Actor{
  override def receive: Receive = {
    case "hi" => println("你好呀!")
  }
}

object Worker{
  def main(args: Array[String]): Unit = {
    val host = "localhost"
    val port = 9999
    val configStr =
      s"""
         |akka.actor.provider="akka.remote.RemoteActorRefProvider"
         |akka.remote.netty.tcp.hostname="$host"
         |akka.remote.netty.tcp.port="$port"
       """.stripMargin
    //通过一个配置工厂解析字符串
    val config = ConfigFactory.parseString(configStr)
    val workeractorsystem = ActorSystem("WORKER_ACTOR_SYSTEM", config)
    val workeractor = workeractorsystem.actorOf(Props[Worker], "WORKER_ACTOR")
    workeractor!("hi")
  }
}

4、主从消息互发

    1)服务端 接收:

  def receive:Receive={
        //Worker发送过来的注册消息
    case "register" => println("===向Master注册成功===")
  }



import akka.actor.{Actor, ActorSystem, Props}
import com.typesafe.config.ConfigFactory

/**
 * 以后要使用actor编程模型进行通信,要跟akka发生关联
 */
class Master extends Actor{
  def receive:Receive={
        //Worker发送过来的注册消息
    case "register" => println("===向Master注册成功===")
  }
}

object Master{
  //入口
  def main(args: Array[String]): Unit = {
    val host = "localhost"
    val port = 8888
    val configStr =
      s"""
        |akka.actor.provider="akka.remote.RemoteActorRefProvider"
        |akka.remote.netty.tcp.hostname="$host"
        |akka.remote.netty.tcp.port="$port"
       """.stripMargin
    val conf = ConfigFactory.parseString(configStr)
    //首先创建一个ActorSystem单例的,在scala中就是一个object
    val actorSystem = ActorSystem("MASTER_ACTOR_SYSTEM", conf)
    //通过ActorSystem创建Actor,通过反射创建Actor的实例
    val masteractor = actorSystem.actorOf(Props[Master], "MASTER_ACTOR")
    //向Actor发送消息
  }
}

 

2)客户端创建与服务端连接

akka.tcp://MASTER_ACTOR_SYSTEM@localhost:8888/user/MASTER_ACTOR

即:服务端侦听的地址端口 + user + Master的ACTOR连接实例

利用Actor中的preStart,开始通信前提前建立与Master的连接,并发送register消息

//在Receive之前执行:执行一次
override def preStart(): Unit = {
  //Worker向Master建立网络连接
  val masterProxy = context.actorSelection("akka.tcp://MASTER_ACTOR_SYSTEM@localhost:8888/user/MASTER_ACTOR")
  //Worker向Master发送注册信息
  masterProxy!"register"
}
/**
 * Worker Actor最好在构造方法执行之后 ,receive方法执行之前,先向Master建立连接
 */
class Worker extends Actor{
  //在Receive之前执行:执行一次
  override def preStart(): Unit = {
    //Worker向Master建立网络连接
    val masterProxy = context.actorSelection("akka.tcp://MASTER_ACTOR_SYSTEM@localhost:8888/user/MASTER_ACTOR")
    //Worker向Master发送注册信息
    masterProxy!"register"
  }

  override def receive: Receive = {
    case "hi" => println("你好呀!")
  }
}

object Worker{
  def main(args: Array[String]): Unit = {
    val host = "localhost"
    val port = 9999
    val configStr =
      s"""
         |akka.actor.provider="akka.remote.RemoteActorRefProvider"
         |akka.remote.netty.tcp.hostname="$host"
         |akka.remote.netty.tcp.port="$port"
       """.stripMargin
    //通过一个配置工厂解析字符串
    val config = ConfigFactory.parseString(configStr)
    val workeractorsystem = ActorSystem("WORKER_ACTOR_SYSTEM", config)
    val workeractor = workeractorsystem.actorOf(Props[Worker], "WORKER_ACTOR")
  }
}

 

©️2020 CSDN 皮肤主题: 技术工厂 设计师:CSDN官方博客 返回首页