Server Memory - Redis
Redis is a server memory that stores data with a key-value pair. It does not depend on the database so it takes the burden of having to manage the data and it is fast. In addition, compared to local storage, another option to store data without depending on a database, it gives us control over the data. Well, enough talking, let's get into it.
Why Do We Use It?
- Fast
- Control over the data
- Persistence (Redis takes a snapshot of the data every other minute, so even if the server goes down, there is less risk of losing the data)
- Option to set the expiry date
Setting Up the Project
Creating a WebAPI Project
How to create .NET web-API
Setting up development tools When working with .NET, we need tools to create a web application. We can download them at the link below. .NET | Free. Cross-platform. Open Source. (microsoft.com) .NET | Free. Cross-platform. Open Source. .NET is a developer
jin-co.tistory.com
Installing Docker
Docker - Installation
To run your application globally, there are many things we have to set up from matching versions between each environment and configurations. Docket is a tool that allows us to manage the application in a container with all the necessary configurations. Do
jin-co.tistory.com
Setting Up Redis
Download the file below and save it in the root of the project
services:
redis:
image: redis:latest
ports:
- 6379:6379
command: ["redis-server", "--appendonly", "yes"]
volumes:
- redis-data:/data
redis-commander:
image: rediscommander/redis-commander:latest
environment:
- REDIS_HOSTS=local:redis:6379
- HTTP_USER=root
- HTTP_PASSWORD=secret
ports:
- 8081:8081
depends_on:
- redis
volumes:
redis-data:
Open the docker desktop and run the containers
Go to the editor and run the command below in the console
docker-compose up
Implementation
Installing Packages
Open 'NugetGallary' and install the Redit package
StackExchange.Redis
Creating Environment Variables
Go to the 'appsettings' file and add a connection string for Redis to use as an environment variable
Setting Up Services
Go to the Program.cs file and add the Redis as a service
builder.Services.AddSingleton<IConnectionMultiplexer>(c =>
{
var opt = ConfigurationOptions.Parse(builder.Configuration.GetConnectionString("Redis"));
return ConnectionMultiplexer.Connect(opt);
});
Using Redis
Let's see how we can use the Redis using the cart feature as an example
Creating Entities
Add a class to store the cart entity
Add ID and items as their properties. For the ID use the string type as this will be provided in the string type
Add another entity for items and add properties as you wish
Go back to the Cart entity and add a constructor. And initialize the item property with an empty list
Creating a Controller
Add a class to set up as a controller
Add a constructor and inject the Redis
▶ Cart List
[HttpGet]
public async Task<ActionResult<Basket>> GetBasket(string id)
{
var data = await _db.StringGetAsync(id);
var basket = data.IsNullOrEmpty ? null : JsonSerializer.Deserialize<Basket>(data);
return basket ?? new Basket(id);
}
▶ Adding or Updating a Cart
[HttpPost]
public async Task<ActionResult<Basket>> UpdateBasket(Basket basket)
{
var UpdatedBasket = await _db.StringSetAsync(basket.Id, JsonSerializer.Serialize(basket), TimeSpan.FromDays(10));
if (UpdatedBasket) return null;
return await GetBasket(basket.Id);
}
▶ Removing a Cart
[HttpDelete]
public async Task DeleteBasket(string id)
{
await _db.KeyDeleteAsync(id);
}
Testing
Move to the API folder
cd /API
And run the app
dotnet watch
Open the docker app and run the server
Open the Redis Commander to see the data
▶ Adding or Updating a Cart
▶ Cart List
▶ Removing a Cart
In this writing, we have seen how we can use Redis.