Redis EXISTS, GET, and SET via C#
In this article, we’ll explore the primary usage of Redis by adding, getting a key/value pair, and checking whether it exists. We’ll show it is done using the Redis CLI and its equivalent when using the C# language; of course, its StackExchange.Redis
API
Introduction and Background
This article assumes that you already have a Redis-server instance where you can connect and play with it. In our previous post (I hope you have enjoyed it), we showed how to connect to a Redis-server instance. Moreover, we’ll explore the command GET
and SET
at least their primary usage. After that, we’ll show how to do that in a Web API application using C#.
Checking Redis Instance
First, make sure you have Redis-server installed on the machine you will use. You can type the following command to verify it.
redis-cli --version
To know the current status of your Redis server before starting. You can try the command below.
sudo service redis-server status
If the Redis server isn’t active, you can type the following command to start it.
sudo service redis-server start
Redis SET and GET Command
These Redis SET and GET commands help us set a key to a particular value and get the current value stored at the key.
Let’s try them out.
SET Sample Syntax
jinLinux% redis-cli
127.0.0.1:6379> SET thisIsMyKey "myKeyValue"
OK
127.0.0.1:6379> SET favoriteFood "adobo"
OK
As you can see, the key holds the string value when using the SET. But if we want to overwrite the previous value, we can retype the last key and set a new value.
Another thing to remember about SET is that it will automatically create a key if one does not already exist.
Let’s see an example below.
127.0.0.1:6379> SET favoriteFood "before adobo now adobo forever :-)"
OK
127.0.0.1:6379> GET favoriteFood
"before adobo now adobo forever :-)"
Another thing to notice is that it returns OK whenever we set a key to a new value. OK is the response when SET has been executed successfully. How’s that?
GET Sample Syntax
This command is evident. It gets the value of a specific key (returns the string inside the key). One thing to note is that when the key doesn’t exist, it returns NIL.
An example of the NIL.
127.0.0.1:6379> GET myKey
(nil)
An example of a successful SET and GET.
127.0.0.1:6379> SET country "Philippines"
OK
127.0.0.1:6379> GET country
"Philippines"
127.0.0.1:6379> SET country "Mexico"
OK
127.0.0.1:6379> GET country
"Mexico"
Redis EXISTS Command
The GET and SET commands are the starting point of learning Redis. However, we can use the EXISTS command if you’re wondering how to check if a key exists.
Another thing to note on this command. It returns one (1) if the key exists; otherwise, it is 0.
Let’s see an example.
127.0.0.1:6379> SET helloworld "Hello Redis"
OK
127.0.0.1:6379> EXISTS helloworld
(integer) 1
127.0.0.1:6379> EXISTS myKey
(integer) 0
127.0.0.1:6379>
Let’s try to see another example.
127.0.0.1:6379> SET myKey1 "key1"
OK
127.0.0.1:6379> SET myKey2 "key2"
OK
127.0.0.1:6379> EXISTS myKey1 myKey2
(integer) 2
127.0.0.1:6379> EXISTS hello1 myKey1 myKey2
(integer) 2
127.0.0.1:6379> EXISTS hello1 myKey1 myKey2 myKey2
(integer) 3
As we can see from the example above, we’re expecting an integer from the EXISTS command. It will be counted multiple times. However, we should be aware that the same existing key is given in the arguments numerous times.
Using EXISTS, GET and SET C# Code Sample
Nice one! You’re here in this section. In this section, we’ll try to convert those Redis CLI examples to their C# equivalent using a minimal API. OK, let’s get started.
Connect To a Redis Server
Connecting to a Redis server is relatively easy. We need to install the Microsoft.Extension.Caching.StackExchangeRedis
.
After that, we need to set up the IConnectionMultiplexer
.
See the example below.
var builder = WebApplication.CreateBuilder(args);
var config = builder.Configuration;
var services = builder.Services;
services.AddSingleton<IConnectionMultiplexer>(option =>
ConnectionMultiplexer.Connect(new ConfigurationOptions
{
EndPoints = { "localhost:6379" },
AbortOnConnectFail = false,
Ssl = false,
Password = ""
}));
var app = builder.Build();
Check Whether a Key Exists
It is because we’re using a minimal API, we’ll create an endpoint where it will check if the key exists.
app.MapGet("/keys/{key}", async
(IConnectionMultiplexer connection, string key) =>
{
var redis = connection.GetDatabase();
var result = await redis.KeyExistsAsync(key);
return new { Message = result ? "Key exists" : "Key doesn't exists" };
});
From the example above, you’ll see that the method KeyExistsAsync
check whether a key exists.
Let’s see it in action.
127.0.0.1:6379> EXISTS key123
(integer) 1
127.0.0.1:6379>
As you can see from above, the key key123 does exist. Let’s test if the endpoint will return a proper message (indicating it exists).
Get an Existing Key Via StringGetAsync
How about this time? We’ll get the value of the key.
Let’s see the endpoint’s code sample first, then see it in action.
app.MapGet("keys/GetValue", async (IConnectionMultiplexer connection, [FromQuery] string key) =>
{
var redis = connection.GetDatabase();
var value = (string)await redis.StringGetAsync(key);
return new { Message = value };
});
As you can see, we used the StringGetAsync
to get the existing key’s value. How easy is that?
Set a New Key Via StringSetAsync
For the last example, Can you guess the name of the method? Yap! It is obviously StringSetAsync
.
Let’s see the endpoint’s code sample below.
public class KeyValue
{
[JsonPropertyName("key")]
public string Key { get; set; }
[JsonPropertyName("value")]
public string Value { get; set; }
}
app.MapPost("/keys/AddKeyValue",
async (IConnectionMultiplexer connection, [FromBody]KeyValue keyValue) =>
{
var redis = connection.GetDatabase();
var result = await redis.StringSetAsync(keyValue.Key, keyValue.Value);
return new { Message = result ? "Added successfully" : $"Unable to add" };
});
The KeyValue
class will represent the data we will pass into the endpoint.
Let’s see it in action.
That’s pretty much it.
Summary
In this post, we have discussed the following
- Checking Redis Instance
- Redis SET and GET Command
- Redis EXISTS Command
- Using EXISTS, GET and SET C# Code Sample
I hope you have enjoyed this article, as I enjoyed it while writing.
You can also find the sample code here on GitHub.
Till next time, happy programming!