项目作者: monix

项目描述 :
Memcached client for Scala
高级语言: Scala
项目地址: git://github.com/monix/shade.git
创建时间: 2013-06-24T11:30:05Z
项目社区:https://github.com/monix/shade

开源协议:MIT License

下载


Shade - Memcached Client for Scala

Build Status
Join the chat at https://gitter.im/monix/shade

Overview

Shade is a Memcached client based on the de-facto Java library
SpyMemcached.

The interface exposed is very Scala-ish, as you have a choice between
making asynchronous calls, with results wrapped as Scala
Futures,
or blocking calls. The performance is stellar as it benefits from the
optimizations that went into SpyMemcached
over the years. Shade also fixes some problems with SpyMemcached’s
architecture, choices that made sense in the context of Java, but
don’t make so much sense in the context of Scala (TODO: add details).

The client is production quality.
Supported for Scala versions: 2.10, 2.11 and 2.12.

Release Notes

Maintainers

These are the people maintaining this project that you can annoy:

Usage From SBT

  1. dependencies += "io.monix" %% "shade" % "1.10.0"

Initializing the Memcached Client

To initialize a Memcached client, you need a configuration object.
Checkout the
Configuration
case class.

  1. import shade.memcached._
  2. import scala.concurrent.ExecutionContext.Implicits.global
  3. val memcached =
  4. Memcached(Configuration("127.0.0.1:11211"))

As you can see, you also need an
ExecutionContext
passed explicitly. As an implementation detail, the execution context represents the
thread-pool in which requests get processed.

Simple non-blocking requests

Useful imports:

  1. import concurrent.duration._ // for specifying timeouts
  2. import concurrent.Future

Setting a key:

  1. val op: Future[Unit] = memcached.set("username", "Alex", 1.minute)

Adding a key that will only set it if the key is missing (returns true
if the key was added, or false if the key was already there):

  1. val op: Future[Boolean] = memcached.add("username", "Alex", 1.minute)

Deleting a key (returns true if a key was deleted, or false if the key
was missing):

  1. val op: Future[Boolean] = memcached.delete("username")

Fetching a key:

  1. val result: Future[Option[String]] = memcached.get[String]("username")

As you can see, for fetching a key the get() method needs an
explicit type parameter, otherwise it doesn’t know how to deserialize
it. More on this below.

Blocking requests

Sometimes working with Futures is painful for quick hacks, therefore
add(), set(), delete() and get() have blocking versions in the
form of awaitXXX():

  1. memcached.awaitGet("username") match {
  2. case Some(username) => println(s"Hello, $username")
  3. case None =>
  4. memcached.awaitSet("username", "Alex", 1.minute)
  5. }

Compare-and-set

Sometimes you want to have some sort of synchronization for modifying
values safely, like incrementing a counter. Memcached supports
Compare-And-Swap
atomic operations and so does this client.

  1. val op: Future[Boolean] =
  2. memcached.compareAndSet("username", Some("Alex"), "Amalia", 1.minute)

This will return either true or false if the operation was a success
or not. But working with compareAndSet is too low level, so the
client also provides these helpers:

  1. def incrementCounter: Future[Int] =
  2. memcached.transformAndGet[Int]("counter", 1.minute) {
  3. case Some(existing) => existing + 1
  4. case None => 1
  5. }

The above returns the new, incremented value. In case you want the old
value to be returned, do this:

  1. def incrementCounter: Future[Option[Int]] =
  2. memcached.getAndTransform[Int]("counter", 1.minute) {
  3. case Some(existing) => existing + 1
  4. case None => 1
  5. }

Serializing/Deserializing

Storing values in Memcached and retrieving values involves serializing
and deserializing those values into bytes. Methods such as get(),
set(), add() take an implicit parameter of type Codec[T] which
is a type-class that specifies how to serialize and deserialize values
of type T.

By default, Shade provides default implementations of Codec[T] for
primitives, such as Strings and numbers. Checkout
Codec.scala to see those
defaults.

For more complex types, a default implementation based on Java’s
ObjectOutputStream
and
ObjectInputStream
exist (also in Codec.scala).

However, because serializing/deserializing values like this is
problematic (you can end up with lots of errors related to the
ClassLoader used), this codec is available as part of the
MemcachedCodecs trait (also in
Codec.scala) and it
either needs to be imported or mixed-in.

The import works like so:

  1. import shade.memcached.MemcachedCodecs._

But this can land you in trouble because of the ClassLoader. For
example in a Play 2.x application, in development mode the code is
recompiled when changes happen and the whole environment gets
restarted. If you do a plain import, you’ll get ClassCastException
or other weird errors. You can solve this by mixing-in
MemcachedCodecs in whatever trait, class or object you want to do
requests, as in:

  1. case class User(id: Int, name: String, age: Int)
  2. trait HelloController extends Controller with MemcachedCodecs {
  3. def memcached: Memcached // to be injected
  4. // a Play 2.2 standard controller action
  5. def userInfo(id: Int) = Action.async {
  6. for (user <- memcached.get[User]("user-" + id)) yield
  7. Ok(views.showUserDetails(user))
  8. }
  9. // ...
  10. }

Or, in case you want to optimize serialization/deserialization, you
can always implement your own Codec[T], like:

  1. // hackish example
  2. implicit object UserCodec extends Codec[User] {
  3. def serialize(user: User): Array[Byte] =
  4. s"${user.id}|${user.name}|${user.age}".getBytes("utf-8")
  5. def deserialize(data: Array[Byte]): User = {
  6. val str = new String(data, "utf-8")
  7. val Array(id, name, age) = str.split("|")
  8. User(id.toInt, name, age.toInt)
  9. }
  10. }