Redis is an in memory store/cache, key/value store. Luckily there’s a Docker image for this.
Let’s run an instance of Redis via Docker on an Ubuntu server
docker run --name myredis -d -p 6379:6379 redis
Oh, how I love Docker (and ofcourse the community who create these images). This will run Redis and return immediately to your host’s command prompt (i.e. we do not go into the instance of Redis).
To run the redis client we’ll need to switch to the instance of the Docker container running Redis and then run the redis command line interface, thus
docker exec -it myredis bash redis-cli
We’ll use this CLI later to view data in the cache.
C# client
There are several Redis client libraries available for .NET/C#, I’m going to go with ServiceStack.Redis, mainly because I’ve been using ServiceStack recently. So create a Console application, add the nuget packages for ServiceStack.Redis and now add the following code
public class Person { public string FirstName { get; set; } public string LastName { get; set; } } class Program { static void Main(string[] args) { var client = new RedisClient("redis://xxx.xxx.xxx.xxx:6379"); client.Add("1234", new Person {FirstName = "Scooby", LastName = "Doo"}); client.Save(); } }
Obviously change xxx.xxx.xxx.xxx to your server ip address.
This code will simply write the Person object to the store against the key 1234. If you have the redis-cli running then you can type
get 1234
this should result in the following result
"{\"FirstName\":\"Scooby\",\"LastName\":\"Doo\"}"
Ofcourse, we now need to use the ServiceStack.Redis client to read our data back. Just use this
var p = client.Get<Person>("1234");
Security
By default Redis has no security set up, hence we didn’t need to specify a user name and password. Obviously in a production environment we’d need to implement such security (or if using Redis via a cloud provider such as Azure).
For our instance we can secure Redis as a whole using the command AUTH. So from redis-cli run
CONFIG SET requirepass "password" AUTH "password"
If you run AUTH “password” and get Err Client sent AUTH, but no password is set you’ll need the CONFIG line, otherwise the AUTH line should work fine. Our client application will need the following changes to the URL
var client = new RedisClient("redis://password@xxx.xxx.xxx.xxx:6379");
To remove the password (if you need to) simple type the following from the redis-cli
CONFIG SET requirepass ""
References