Redis in Web API

Full source code available here.

In an earlier post, I showed how to use Redis in console application, with very little effort it can also be used in a Web API application.

Start by adding StackExchange.Redis to the application.

Startup.cs

Inside the Startup.cs add a using -

using StackExchange.Redis;

In ConfigureServices(..) add -

var multiplexer = ConnectionMultiplexer.Connect("localhost");
services.AddSingleton<IConnectionMultiplexer>(multiplexer);

The Controller

Add a controller called ValuesController, add the same using statement as above.

Then add a local variable for the connectionMultiplexer and update the constructor for dependency injection -

private readonly IConnectionMultiplexer _connectionMultiplexer;
private readonly IDatabase _redis;

public ValuesController(IConnectionMultiplexer connectionMultiplexer)
{
    _connectionMultiplexer = connectionMultiplexer;
    _redis = _connectionMultiplexer.GetDatabase();
}

That’s all the plumbing in place.

Add the GET, POST, PUT, and DELETE methods.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
[HttpGet("{key}")]
public async Task<IActionResult> Get(string key)
{
    return Ok((await _redis.StringGetAsync(key)).ToString());
}

[HttpPost]
public async Task<IActionResult> Post([FromBody] KeyValue keyValue)
{
    await _redis.StringSetAsync(keyValue.Key, keyValue.Value);
    return Created("", keyValue.Value);
}

[HttpPut("{key}")]
public async Task<IActionResult> Put(string key, [FromBody] string value)
{
    await _redis.StringSetAsync(key, value);
    return NoContent();
}

[HttpDelete("{key}")]
public async Task<IActionResult> Delete(string key)
{
    await _redis.KeyDeleteAsync(key);
    return NoContent();
}

To make life easy, in the Post method (line 9 above) I added a KeyValue type -

public class KeyValue
{
    public string Key { get; set; }
    public string Value { get; set; }
}

Testing it out with REST Client

If you don’t have Redis installed, use a Docker container.

docker pull redis
docker run --name my-redis -p 6379:6379 redis

In the attached zip file there is a VS Code REST Client example file that performs exercises all the methods on the controller.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
POST http://localhost:5000/values HTTP/1.1
content-type: application/json

{
    "key": "a",
    "value": "bbb"
}

###
PUT http://localhost:5000/values/a HTTP/1.1
content-type: application/json

"ccc"

###
GET http://localhost:5000/values/a

###

DELETE http://localhost:5000/values/a

Full source code available here

comments powered by Disqus

Related