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[HttpGet("{key}")]
2public async Task<IActionResult> Get(string key)
3{
4 return Ok((await _redis.StringGetAsync(key)).ToString());
5}
6
7[HttpPost]
8public async Task<IActionResult> Post([FromBody] KeyValue keyValue)
9{
10 await _redis.StringSetAsync(keyValue.Key, keyValue.Value);
11 return Created("", keyValue.Value);
12}
13
14[HttpPut("{key}")]
15public async Task<IActionResult> Put(string key, [FromBody] string value)
16{
17 await _redis.StringSetAsync(key, value);
18 return NoContent();
19}
20
21[HttpDelete("{key}")]
22public async Task<IActionResult> Delete(string key)
23{
24 await _redis.KeyDeleteAsync(key);
25 return NoContent();
26}
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.
1POST http://localhost:5000/values HTTP/1.1
2content-type: application/json
3
4{
5 "key": "a",
6 "value": "bbb"
7}
8
9###
10PUT http://localhost:5000/values/a HTTP/1.1
11content-type: application/json
12
13"ccc"
14
15###
16GET http://localhost:5000/values/a
17
18###
19
20DELETE http://localhost:5000/values/a
Full source code available here