本文整理汇总了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
}
}
示例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)
}
}
}
示例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])
}
}
}
示例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 = ???
}
示例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))
}
示例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)
}
}
)
}
}
示例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); ()
}
}
}
示例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
()
}
}
示例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()
}
}
}
示例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
}
}
}
}
示例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
}
}
}
}
示例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)
}
}
}