Redis EXISTS, GET, and SET via C#
Tags: redis, aspnetcore, csharp, dotnetcore
Published: 2023-07-08 05:22:22

---
title: Redis EXISTS, GET, and SET via C#
published: true
date: 2023-04-10 05:51:27 UTC
tags: redis,aspnetcore,csharp,dotnetcore
canonical_url: https://lock29down.medium.com/redis-get-and-set-via-c-de54115a507c
---

#### 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.RedisAPI

![](https://cdn-images-1.medium.com/max/1024/0*NdyK0WnaW70abkQV)
_Photo by Christina @ wocintechchat.com on Unsplash_

### 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](https://dev.to/jindeveloper/how-to-connect-to-redis-via-c-1ll0-temp-slug-1610472) (_I hope you have enjoyed it_), we showed how to connect to a Redis-server instance. Moreover, we’ll explore the command GETand 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`

![](https://cdn-images-1.medium.com/max/1024/1*aTHW8uN2Qsl1d7SjPOufwA.png)

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

```shell
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.

```shell
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.

```shell
127.0.0.1:6379> GET myKey
(nil)
```

An example of a successful SET and GET.

```shell
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.

```shell
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.

```shell
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.

```csharp
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.

```csharp
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.

```shell
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_).

![](https://cdn-images-1.medium.com/max/1024/1*D85MrMJWy4l4sfaO7RkQ-Q.gif)

#### 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.

```csharp
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 };
});
```

![](https://cdn-images-1.medium.com/max/1024/1*SIczz-AF_h1yIr7PHQ_pgA.gif)

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.

```csharp
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 KeyValueclass will represent the data we will pass into the endpoint.

Let’s see it in action.

![](https://cdn-images-1.medium.com/max/1024/1*3p8LVA-BXfjvstZa1YpbaQ.gif)

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](https://github.com/jindeveloper/RedisCsharpSample/tree/master).

Till next time, happy programming!