• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Scala SerializationExtension类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Scala中akka.serialization.SerializationExtension的典型用法代码示例。如果您正苦于以下问题:Scala SerializationExtension类的具体用法?Scala SerializationExtension怎么用?Scala SerializationExtension使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了SerializationExtension类的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。

示例1: serialize

//设置package包名称以及导入依赖的类
package akka.remote

import akka.remote.WireFormats._
import com.google.protobuf.ByteString
import akka.actor.ExtendedActorSystem
import akka.serialization.SerializationExtension


  def serialize(system: ExtendedActorSystem, message: AnyRef): SerializedMessage = {
    val s = SerializationExtension(system)
    val serializer = s.findSerializerFor(message)
    val builder = SerializedMessage.newBuilder
    builder.setMessage(ByteString.copyFrom(serializer.toBinary(message)))
    builder.setSerializerId(serializer.identifier)
    if (serializer.includeManifest)
      builder.setMessageManifest(ByteString.copyFromUtf8(message.getClass.getName))
    builder.build
  }
} 
开发者ID:love1314sea,项目名称:akka-2.3.16,代码行数:20,代码来源:MessageSerializer.scala


示例2: MessageContainerSerializerSpec

//设置package包名称以及导入依赖的类
package akka.remote.serialization

import akka.serialization.SerializationExtension
import com.typesafe.config.ConfigFactory
import akka.testkit.AkkaSpec
import akka.actor.ActorSelectionMessage
import akka.actor.SelectChildName
import akka.actor.SelectParent
import akka.actor.SelectChildPattern
import akka.util.Helpers

@org.junit.runner.RunWith(classOf[org.scalatest.junit.JUnitRunner])
class MessageContainerSerializerSpec extends AkkaSpec {

  val ser = SerializationExtension(system)

  "DaemonMsgCreateSerializer" must {

    "resolve serializer for ActorSelectionMessage" in {
      ser.serializerFor(classOf[ActorSelectionMessage]).getClass should be(classOf[MessageContainerSerializer])
    }

    "serialize and de-serialize ActorSelectionMessage" in {
      verifySerialization(ActorSelectionMessage("hello", Vector(
        SelectChildName("user"), SelectChildName("a"), SelectChildName("b"), SelectParent,
        SelectChildPattern("*"), SelectChildName("c")), wildcardFanOut = true))
    }

    def verifySerialization(msg: AnyRef): Unit = {
      ser.deserialize(ser.serialize(msg).get, msg.getClass).get should be(msg)
    }

  }
} 
开发者ID:love1314sea,项目名称:akka-2.3.16,代码行数:35,代码来源:MessageContainerSerializerSpec.scala


示例3: ProtobufSerializerSpec

//设置package包名称以及导入依赖的类
package akka.remote.serialization

import akka.serialization.SerializationExtension
import akka.testkit.AkkaSpec
import akka.remote.WireFormats.SerializedMessage
import akka.remote.ProtobufProtocol.MyMessage

@org.junit.runner.RunWith(classOf[org.scalatest.junit.JUnitRunner])
class ProtobufSerializerSpec extends AkkaSpec {

  val ser = SerializationExtension(system)

  "Serialization" must {

    "resolve protobuf serializer" in {
      ser.serializerFor(classOf[SerializedMessage]).getClass should be(classOf[ProtobufSerializer])
      ser.serializerFor(classOf[MyMessage]).getClass should be(classOf[ProtobufSerializer])
    }

  }
} 
开发者ID:love1314sea,项目名称:akka-2.3.16,代码行数:22,代码来源:ProtobufSerializerSpec.scala


示例4: PersistenceSerializerDocSpec

//设置package包名称以及导入依赖的类
package docs.persistence

import com.typesafe.config._
import scala.concurrent.duration._
import org.scalatest.WordSpec
import akka.actor.ActorSystem
import akka.serialization.{ Serializer, SerializationExtension }
import akka.testkit.TestKit

class PersistenceSerializerDocSpec extends WordSpec {

  val customSerializerConfig =
    """
      //#custom-serializer-config
      akka.actor {
        serializers {
          my-payload = "docs.persistence.MyPayloadSerializer"
          my-snapshot = "docs.persistence.MySnapshotSerializer"
        }
        serialization-bindings {
          "docs.persistence.MyPayload" = my-payload
          "docs.persistence.MySnapshot" = my-snapshot
        }
      }
      //#custom-serializer-config
    """.stripMargin

  val system = ActorSystem("PersistenceSerializerDocSpec", ConfigFactory.parseString(customSerializerConfig))
  try {
    SerializationExtension(system)
  } finally {
    TestKit.shutdownActorSystem(system, 10.seconds, false)
  }
}

class MyPayload
class MySnapshot

class MyPayloadSerializer extends Serializer {
  def identifier: Int = 77124
  def includeManifest: Boolean = false
  def toBinary(o: AnyRef): Array[Byte] = ???
  def fromBinary(bytes: Array[Byte], manifest: Option[Class[_]]): AnyRef = ???
}

class MySnapshotSerializer extends Serializer {
  def identifier: Int = 77125
  def includeManifest: Boolean = false
  def toBinary(o: AnyRef): Array[Byte] = ???
  def fromBinary(bytes: Array[Byte], manifest: Option[Class[_]]): AnyRef = ???
} 
开发者ID:love1314sea,项目名称:akka-2.3.16,代码行数:52,代码来源:PersistenceSerializerDocSpec.scala


示例5: ServerChannelActor

//设置package包名称以及导入依赖的类
package com.naoh.beef.internal

import akka.actor.Actor
import akka.actor.ActorRef
import akka.actor.Props
import akka.serialization.SerializationExtension
import com.naoh.beef.proto.network.RequestChannel


class ServerChannelActor(selector: ActorRef, name: String) extends Actor {

  import Network._

  implicit val extendedSystem = SerializationExtension(context.system).system

  val pending = ScalaDeque.empty[ActorRef]
  val buffer = ScalaDeque.empty[ServerChannel]

  override def receive: Receive = {
    case [email protected](`name`) =>
      buffer.poll.fold[Unit] {
        pending add sender()
        selector ! ServerSelectorActor.Find(name)
      } { channel =>
        sender() ! channel
      }
    case ch: ServerChannel =>
      pending.poll.fold[Unit](
        buffer add ch
      ) { ref =>
        ref ! ch
      }
    case ProtoServerChannel(ch) =>
      self forward ch
    case [email protected](region, ref) =>
      ref ! RequestChannel(name)
    case NotFound(`name`) =>
      pending.poll.foreach(_ ! NotFound(name))
    case msg =>
  }

}

object ServerChannelActor {
  def props(selector: ActorRef, name: String) = Props(new ServerChannelActor(selector, name))

} 
开发者ID:naoh87,项目名称:grpc-scala-experiment,代码行数:48,代码来源:ServerChannelActor.scala


示例6: CouchbaseSnapshotStore

//设置package包名称以及导入依赖的类
package akka.persistence.couchbase.snapshot

import java.util.concurrent.TimeUnit

import akka.actor.ActorLogging
import akka.persistence.couchbase.{CouchbaseExtension, Message}
import akka.persistence.serialization.Snapshot
import akka.persistence.snapshot.SnapshotStore
import akka.persistence.{SelectedSnapshot, SnapshotMetadata, SnapshotSelectionCriteria}
import akka.serialization.SerializationExtension
import com.couchbase.client.java.view.ViewRow

import scala.collection.JavaConverters._
import scala.concurrent.Future
import scala.util.Try

class CouchbaseSnapshotStore extends SnapshotStore with CouchbaseStatements with ActorLogging {

  implicit val executionContext = context.dispatcher

  val couchbase = CouchbaseExtension(context.system)
  val serialization = SerializationExtension(context.system)

  def config = couchbase.snapshotStoreConfig

  def bucket = couchbase.snapshotStoreBucket

  
  override def saveAsync(metadata: SnapshotMetadata, data: Any): Future[Unit] = {
    Future.fromTry[Unit](
      Try {
        val snapshot = Snapshot(data)
        val message = Message(serialization.findSerializerFor(snapshot).toBinary(snapshot))
        SnapshotMessage.create(metadata, message)
      } flatMap executeSave
    )
  }

  override def deleteAsync(metadata: SnapshotMetadata): Future[Unit] = {
    Future.fromTry[Unit](
      Try {
        bucket.remove(SnapshotMessageKey.fromMetadata(metadata).value)
      }
    )
  }

  override def deleteAsync(persistenceId: String, criteria: SnapshotSelectionCriteria): Future[Unit] = {
    Future.fromTry[Unit](
      Try {
        query(persistenceId, criteria, Integer.MAX_VALUE).foreach { snapshotMessage =>
          bucket.remove(SnapshotMessageKey.fromMetadata(snapshotMessage.metadata).value)
        }
      }
    )
  }
} 
开发者ID:Product-Foundry,项目名称:akka-persistence-couchbase,代码行数:57,代码来源:CouchbaseSnapshotStore.scala


示例7: PgAsyncSnapshotStore

//设置package包名称以及导入依赖的类
package akka.persistence.pg.snapshot

import akka.actor.{ActorLogging, ActorSystem}
import akka.persistence.pg.{PgConfig, PgExtension}
import akka.persistence.serialization.Snapshot
import akka.persistence.{SelectedSnapshot, SnapshotMetadata, SnapshotSelectionCriteria}
import akka.serialization.{Serialization, SerializationExtension}

import scala.concurrent.Future

class PgAsyncSnapshotStore extends akka.persistence.snapshot.SnapshotStore
  with PgSnapshotStore
  with ActorLogging
  with PgConfig {

  implicit val system: ActorSystem = context.system
  implicit val executionContext = context.system.dispatcher

  override val serialization: Serialization = SerializationExtension(context.system)
  override lazy val pluginConfig = PgExtension(context.system).pluginConfig

  import driver.api._

  override def loadAsync(persistenceId: String, criteria: SnapshotSelectionCriteria): Future[Option[SelectedSnapshot]] = {
    log.debug(s"loading snapshot for persistenceId: {}, criteria: {}", persistenceId, criteria)
    selectMostRecentSnapshotFor(persistenceId, criteria)
  }

  override def saveAsync(metadata: SnapshotMetadata, snapshot: Any): Future[Unit] = {
    log.debug(s"saving snapshot for metadata {}",metadata)
    val serialized: Array[Byte] = serialization.serialize(Snapshot(snapshot)).get
    database.run(snapshotsQuery(metadata).length
      .result.flatMap { result: Int =>
        val v = (metadata.persistenceId, metadata.sequenceNr, metadata.timestamp, serialized)
        if (result > 0) {
          snapshotsQuery(metadata).update(v)
        } else {
          snapshots += v
        }
    }).map { _ => () }
  }

  override def deleteAsync(metadata: SnapshotMetadata): Future[Unit] = {
    log.debug(s"deleting: {}",metadata)
    deleteSnapshot(metadata).map { _ =>
      log.debug(s"deleted snapshot {}",metadata)
    }
  }

  override def deleteAsync(persistenceId: String, criteria: SnapshotSelectionCriteria): Future[Unit] = {
    log.debug(s"deleting for persistenceId: {} and criteria: {}",persistenceId, criteria)
    database.run(selectSnapshotsQuery(persistenceId, criteria).delete).map { deleted =>
      log.debug(s"deleted {} snapshots", deleted); ()
    }
  }

} 
开发者ID:WegenenVerkeer,项目名称:akka-persistence-postgresql,代码行数:58,代码来源:PgAsyncSnapshotStore.scala


示例8: PgSnapshotStoreSpec

//设置package包名称以及导入依赖的类
package akka.persistence.pg.testkit

import akka.persistence.pg.snapshot.PgSnapshotStore
import akka.persistence.pg.{PgExtension, PgConfig}
import akka.persistence.pg.util.RecreateSchema
import akka.persistence.snapshot.SnapshotStoreSpec
import akka.serialization.{Serialization, SerializationExtension}
import com.typesafe.config.ConfigFactory
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.time.{Milliseconds, Second, Span}

import scala.language.postfixOps

class PgSnapshotStoreSpec extends SnapshotStoreSpec(ConfigFactory.load("pg-application.conf"))
  with PgSnapshotStore
  with RecreateSchema
  with ScalaFutures
  with PgConfig {

  override implicit val patienceConfig = PatienceConfig(timeout = Span(1, Second), interval = Span(100, Milliseconds))

  override lazy val pluginConfig = PgExtension(system).pluginConfig
  override val serialization: Serialization = SerializationExtension(system)

  import driver.api._

  override def beforeAll() {
    database.run(recreateSchema.andThen(snapshots.schema.create)).futureValue
    super.beforeAll()
  }

  override protected def afterAll(): Unit = {
    system.terminate()
    system.whenTerminated.futureValue
    ()
  }


} 
开发者ID:WegenenVerkeer,项目名称:akka-persistence-postgresql,代码行数:40,代码来源:PgSnapshotStoreSpec.scala


示例9: MyConfluentRegistry

//设置package包名称以及导入依赖的类
package io.amient.affinity.systemtests.avro

import akka.actor.ActorSystem
import akka.serialization.SerializationExtension
import com.typesafe.config.{Config, ConfigFactory, ConfigValueFactory}
import io.amient.affinity.core.serde.avro._
import io.amient.affinity.core.serde.avro.schema.CfAvroSchemaRegistry
import io.amient.affinity.testutil.SystemTestBaseWithConfluentRegistry
import org.scalatest.FlatSpec


class MyConfluentRegistry(config: Config) extends CfAvroSchemaRegistry(config) {
  register(classOf[ID])
  register(classOf[Base])
  register(classOf[Composite])
}

class CfRegistryTest extends FlatSpec with SystemTestBaseWithConfluentRegistry {

  val config = configure(ConfigFactory.defaultReference)
    .withValue(AvroSerde.CONFIG_PROVIDER_CLASS, ConfigValueFactory.fromAnyRef(classOf[MyConfluentRegistry].getName))

  assert(config.getString(CfAvroSchemaRegistry.CONFIG_CF_REGISTRY_URL_BASE) == registryUrl)

  override def numPartitions = 2

  "Confluent Schema Registry Provider" should "be available via akka SerializationExtension" in {
    val system = ActorSystem.create("CfTest", config)
    try {
      val serialization = SerializationExtension(system)
      val serde = serialization.serializerFor(classOf[ID])
      assert(serde.fromBinary(serde.toBinary(ID(101))) == ID(101))
    } finally {
      system.terminate()
    }
  }
} 
开发者ID:amient,项目名称:affinity,代码行数:38,代码来源:CfRegistryTest.scala


示例10: PersistenceMessageSerializerSpec

//设置package包名称以及导入依赖的类
package com.lightbend.lagom.internal.javadsl.persistence.protobuf

import java.io.NotSerializableException

import scala.concurrent.duration._
import akka.actor.ExtendedActorSystem
import akka.serialization.SerializationExtension
import com.lightbend.lagom.internal.persistence.cluster.ClusterDistribution.EnsureActive
import com.lightbend.lagom.persistence.ActorSystemSpec
import com.lightbend.lagom.javadsl.persistence.CommandEnvelope
import com.lightbend.lagom.javadsl.persistence.PersistentEntity.InvalidCommandException
import com.lightbend.lagom.javadsl.persistence.PersistentEntity.PersistException
import com.lightbend.lagom.javadsl.persistence.PersistentEntity.UnhandledCommandException
import com.lightbend.lagom.javadsl.persistence.PersistentEntityRef
import com.lightbend.lagom.javadsl.persistence.TestEntity

class PersistenceMessageSerializerSpec extends ActorSystemSpec {

  val serializer = new PersistenceMessageSerializer(system.asInstanceOf[ExtendedActorSystem])

  def checkSerialization(obj: AnyRef): Unit = {
    // check that it is configured
    SerializationExtension(system).serializerFor(obj.getClass).getClass should be(classOf[PersistenceMessageSerializer])

    // verify serialization-deserialization round trip
    val blob = serializer.toBinary(obj)
    val obj2 = serializer.fromBinary(blob, serializer.manifest(obj))
    obj2 should be(obj)
  }

  "PersistenceMessageSerializer" must {

    "serialize CommandEnvelope" in {
      checkSerialization(CommandEnvelope("entityId", TestEntity.Add.of("a")))
    }

    "serialize EnsureActive" in {
      checkSerialization(EnsureActive("foo"))
    }

    "serialize InvalidCommandException" in {
      checkSerialization(InvalidCommandException("wrong"))
    }

    "serialize UnhandledCommandException" in {
      checkSerialization(UnhandledCommandException("unhandled"))
    }

    "serialize PersistException" in {
      checkSerialization(PersistException("not stored"))
    }

    "not serialize PersistentEntityRef" in {
      intercept[NotSerializableException] {
        SerializationExtension(system).serialize(new PersistentEntityRef[String]("abc", system.deadLetters, system, 5.seconds)).get
      }
    }
  }

} 
开发者ID:lagom,项目名称:lagom,代码行数:61,代码来源:PersistenceMessageSerializerSpec.scala


示例11: PersistenceMessageSerializerSpec

//设置package包名称以及导入依赖的类
package com.lightbend.lagom.internal.scaladsl.persistence.protobuf

import java.io.NotSerializableException

import scala.concurrent.duration._
import akka.actor.ExtendedActorSystem
import akka.serialization.SerializationExtension
import com.lightbend.lagom.internal.persistence.cluster.ClusterDistribution.EnsureActive
import com.lightbend.lagom.persistence.ActorSystemSpec
import com.lightbend.lagom.scaladsl.persistence.CommandEnvelope
import com.lightbend.lagom.scaladsl.persistence.PersistentEntity.InvalidCommandException
import com.lightbend.lagom.scaladsl.persistence.PersistentEntity.PersistException
import com.lightbend.lagom.scaladsl.persistence.PersistentEntity.UnhandledCommandException
import com.lightbend.lagom.scaladsl.persistence.PersistentEntityRef
import com.lightbend.lagom.scaladsl.persistence.TestEntity
import com.typesafe.config.ConfigFactory

class PersistenceMessageSerializerSpec extends ActorSystemSpec {

  val serializer = new PersistenceMessageSerializer(system.asInstanceOf[ExtendedActorSystem])

  def checkSerialization(obj: AnyRef): Unit = {
    // check that it is configured
    SerializationExtension(system).serializerFor(obj.getClass).getClass should be(classOf[PersistenceMessageSerializer])

    // verify serialization-deserialization round trip
    val blob = serializer.toBinary(obj)
    val obj2 = serializer.fromBinary(blob, serializer.manifest(obj))
    obj2 should be(obj)
  }

  "PersistenceMessageSerializer" must {

    "serialize CommandEnvelope" in {
      checkSerialization(CommandEnvelope("entityId", TestEntity.Add("a")))
    }

    "serialize EnsureActive" in {
      checkSerialization(EnsureActive("foo"))
    }

    "serialize InvalidCommandException" in {
      checkSerialization(InvalidCommandException("wrong"))
    }

    "serialize UnhandledCommandException" in {
      checkSerialization(UnhandledCommandException("unhandled"))
    }

    "serialize PersistException" in {
      checkSerialization(PersistException("not stored"))
    }

    "not serialize PersistentEntityRef" in {
      intercept[NotSerializableException] {
        SerializationExtension(system).serialize(new PersistentEntityRef[String]("abc", system.deadLetters, system, 5.seconds)).get
      }
    }
  }

} 
开发者ID:lagom,项目名称:lagom,代码行数:62,代码来源:PersistenceMessageSerializerSpec.scala


示例12: KafkaMessageSerializer

//设置package包名称以及导入依赖的类
package nl.tradecloud.kafka

import akka.actor.ActorSystem
import akka.protobuf.ByteString
import akka.remote.WireFormats.SerializedMessage
import akka.serialization.{SerializationExtension, SerializerWithStringManifest}
import org.apache.kafka.common.errors.SerializationException

import scala.util.control.NonFatal

// COPIED FROM AKKA: https://github.com/akka/akka/blob/master/akka-remote/src/main/scala/akka/remote/MessageSerializer.scala
object KafkaMessageSerializer {
  
  def serialize(system: ActorSystem, message: AnyRef): SerializedMessage = {
    val s = SerializationExtension(system)
    val serializer = s.findSerializerFor(message)
    val builder = SerializedMessage.newBuilder

    try {
      builder.setMessage(ByteString.copyFrom(serializer.toBinary(message)))
      builder.setSerializerId(serializer.identifier)
      serializer match {
        case ser2: SerializerWithStringManifest =>
          val manifest = ser2.manifest(message)
          if (manifest != "")
            builder.setMessageManifest(ByteString.copyFromUtf8(manifest))
        case _ =>
          if (serializer.includeManifest)
            builder.setMessageManifest(ByteString.copyFromUtf8(message.getClass.getName))
      }
      builder.build
    } catch {
      case NonFatal(e) =>
        throw new SerializationException(s"Failed to serialize akka message [${message.getClass}] " +
          s"using serializer [${serializer.getClass}].", e)
    }
  }
} 
开发者ID:tradecloud,项目名称:kafka-akka-extension,代码行数:39,代码来源:KafkaMessageSerializer.scala



注:本文中的akka.serialization.SerializationExtension类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Scala ToolBox类代码示例发布时间:2022-05-23
下一篇:
Scala DBApi类代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap