Skip to content

Functional Memcached for Scala 🕵️

License

Notifications You must be signed in to change notification settings

maginepro/spies

Repository files navigation

🕵️ Spies

Spies is a functional Memcached library based on SpyMemcached and Cats Effect.
The library is inspired by Shade and ScalaCache but with a pure functional interface.

Usage

You can add the following lines to build.sbt to use the library.

libraryDependencies ++= Seq(
  "com.magine" %% "spies" % spiesVersion,
  "com.magine" %% "spies-circe" % spiesVersion
)

Make sure to replace spiesVersion with a release version.

Quick Example

Following is an example of how to count to 100 using 100 parallel increment-by-one updates.

import cats.effect.IO
import cats.effect.IOApp
import cats.syntax.all._
import scala.concurrent.duration._

object Main extends IOApp.Simple {
  override def run: IO[Unit] =
    Memcached.localhost[IO].use { memcached =>
      val increment = memcached.update[Int]("key", 10.seconds)(_.fold(1)(_ + 1))
      val updates = List.fill(100)(increment).parSequence_
      val get = memcached.get[Int]("key")
      updates >> get.flatMap(IO.println)
    }
}

The example demonstrates support for check-and-set (CAS) operations. Some updates will fail on the first attempt (since a different update was performed in-between the get and the update), but these updates will automatically be retried.

Note the example communicates with a local Memcached instance, using the default protocol. When dealing with Memcached clusters, you can use Memcached.ketama to use the Ketama consistent hashing algorithm to consistently map keys to servers, even when Memcached servers are added or removed from the cluster (only a small proportion of keys end up mapping to different servers).

Spies is based on the Amazon ElastiCache Cluster Client which supports node auto discovery by default.