RedisCluster (redis_cluster v0.8.0)
View SourceThis module is a thin wrapper around the RedisCluster.Cluster module.
First, you will need a module to use this module.
defmodule MyApp.Redis do
use RedisCluster, otp_app: :my_app
endThen you need to include the relevant config in your config.exs (or runtime.exs):
config :my_app, MyApp.Redis,
host: "localhost",
port: 6379,
pool_size: 10Ideally, your host should a configuration endpoint for ElastiCache (or equivalent).
This endpoint picks a random node in the cluster to connect to for discovering the cluster.
Your module will have basic Redis functions like get, set, and delete.
You can also run arbitrary Redis commands with command and pipeline.
You may also want to include other convenience functions in your module:
defmodule MyApp.Redis do
use RedisCluster, otp_app: :my_app
def hget(key, field) do
# Implementation here...
end
def hgetall(key) do
# Implementation here...
end
def hset(key, field, value) do
# Implementation here...
end
endDon't forget to start the Redis cluster in your application supervision tree, probably in lib/my_app/application.ex:
def start(_type, _args) do
children = [
MyApp.Redis,
# Other children...
]
opts = [strategy: :one_for_one, name: MyApp.Supervisor]
Supervisor.start_link(children, opts)
endAlternatively, you can use the RedisCluster.Cluster module directly.
config = %RedisCluster.Configuration{
host: "localhost",
port: 6379,
pool_size: 3,
name: Test.Redis,
registry: Test.Redis.Registry__,
pool: Test.Redis.Pool__,
cluster: Test.Redis.Cluster__,
shard_discovery: Test.Redis.ShardDiscovery__
}
{:ok, pid} = RedisCluster.Cluster.start_link(config)
RedisCluster.Cluster.set(config, "answer", 42)
RedisCluster.Cluster.get(config, "answer")This can be useful for testing, Livebook demos, or dynamically connecting to Redis clusters.