-
Notifications
You must be signed in to change notification settings - Fork 8
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add initial setup for DotnetRedisCacheAPI project
- Added Visual Studio solution file `DotnetRedisCacheAPI.sln`. - Added `appsettings.Development.json` and `appsettings.json` for logging and allowed hosts configuration. - Created `DotnetRedisCacheAPI.csproj` targeting .NET 9.0 with necessary package references. - Added `DotnetRedisCacheAPI.http` for API endpoint testing. - Updated `Program.cs` to configure services including controllers, OpenAPI, HTTP client, Redis, and JSONPlaceholder. - Added `JsonPlaceholderController.cs` for API endpoints to fetch data from JSONPlaceholder. - Created `JsonPlaceholderDtos.cs` for data transfer objects. - Added `launchSettings.json` for launch profiles configuration. - Created interfaces `IJsonPlaceholderService.cs` and `IRedisService.cs`. - Implemented `JsonPlaceholderService.cs` for fetching and caching data. - Implemented `RedisService.cs` for Redis interactions.
- Loading branch information
1 parent
e25e4c0
commit fec85eb
Showing
13 changed files
with
354 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
|
||
Microsoft Visual Studio Solution File, Format Version 12.00 | ||
# Visual Studio Version 17 | ||
VisualStudioVersion = 17.12.35506.116 d17.12 | ||
MinimumVisualStudioVersion = 10.0.40219.1 | ||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DotnetRedisCacheAPI", "DotnetRedisCacheAPI\DotnetRedisCacheAPI.csproj", "{FB59AB68-C7C8-4447-859E-3D221834D0CA}" | ||
EndProject | ||
Global | ||
GlobalSection(SolutionConfigurationPlatforms) = preSolution | ||
Debug|Any CPU = Debug|Any CPU | ||
Release|Any CPU = Release|Any CPU | ||
EndGlobalSection | ||
GlobalSection(ProjectConfigurationPlatforms) = postSolution | ||
{FB59AB68-C7C8-4447-859E-3D221834D0CA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU | ||
{FB59AB68-C7C8-4447-859E-3D221834D0CA}.Debug|Any CPU.Build.0 = Debug|Any CPU | ||
{FB59AB68-C7C8-4447-859E-3D221834D0CA}.Release|Any CPU.ActiveCfg = Release|Any CPU | ||
{FB59AB68-C7C8-4447-859E-3D221834D0CA}.Release|Any CPU.Build.0 = Release|Any CPU | ||
EndGlobalSection | ||
GlobalSection(SolutionProperties) = preSolution | ||
HideSolutionNode = FALSE | ||
EndGlobalSection | ||
EndGlobal |
74 changes: 74 additions & 0 deletions
74
DotnetRedisCacheAPI/DotnetRedisCacheAPI/Controllers/JsonPlaceholderController.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,74 @@ | ||
using DotnetRedisCacheAPI.Service; | ||
using Microsoft.AspNetCore.Mvc; | ||
|
||
namespace DotnetRedisCacheAPI.Controllers | ||
{ | ||
[ApiController] | ||
[Route("api/")] | ||
public class JsonPlaceholderController : Controller | ||
{ | ||
private readonly IJsonPlaceholderService _jsonPlaceholderService; | ||
|
||
public JsonPlaceholderController(IJsonPlaceholderService jsonPlaceholderService) | ||
{ | ||
_jsonPlaceholderService = jsonPlaceholderService; | ||
} | ||
|
||
|
||
[HttpGet("post")] | ||
public async Task<IActionResult> GetAllPosts() | ||
{ | ||
var post = await _jsonPlaceholderService.GetAllPosts(); | ||
return Ok(post); | ||
} | ||
|
||
[HttpGet("comments")] | ||
|
||
public async Task<IActionResult> GetAllComments() | ||
{ | ||
var comments = await _jsonPlaceholderService.GetAllComments(); | ||
return Ok(comments); | ||
} | ||
|
||
|
||
[HttpGet("albums")] | ||
public async Task<IActionResult> GetAllAlbums() | ||
{ | ||
var albums = await _jsonPlaceholderService.GetAllAlbums(); | ||
return Ok(albums); | ||
} | ||
|
||
|
||
[HttpGet("photos")] | ||
public async Task<IActionResult> GetAllPhotos() | ||
{ | ||
var photos = await _jsonPlaceholderService.GetAllPhotos(); | ||
return Ok(photos); | ||
} | ||
|
||
|
||
|
||
[HttpGet("todos")] | ||
|
||
public async Task<IActionResult> GetAllTodos() | ||
{ | ||
var todos = await _jsonPlaceholderService.GetAllTodos(); | ||
return Ok(todos); | ||
} | ||
|
||
|
||
[HttpGet("users")] | ||
|
||
public async Task<IActionResult> GetAllUser() | ||
{ | ||
var users = await _jsonPlaceholderService.GetAllUsers(); | ||
return Ok(users); | ||
} | ||
|
||
|
||
|
||
|
||
|
||
|
||
} | ||
} |
16 changes: 16 additions & 0 deletions
16
DotnetRedisCacheAPI/DotnetRedisCacheAPI/DotnetRedisCacheAPI.csproj
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
<Project Sdk="Microsoft.NET.Sdk.Web"> | ||
|
||
<PropertyGroup> | ||
<TargetFramework>net9.0</TargetFramework> | ||
<Nullable>enable</Nullable> | ||
<ImplicitUsings>enable</ImplicitUsings> | ||
</PropertyGroup> | ||
|
||
<ItemGroup> | ||
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="9.0.1" /> | ||
<PackageReference Include="Microsoft.Extensions.Caching.StackExchangeRedis" Version="9.0.1" /> | ||
<PackageReference Include="Scalar.AspNetCore" Version="2.0.4" /> | ||
<PackageReference Include="StackExchange.Redis" Version="2.8.24" /> | ||
</ItemGroup> | ||
|
||
</Project> |
6 changes: 6 additions & 0 deletions
6
DotnetRedisCacheAPI/DotnetRedisCacheAPI/DotnetRedisCacheAPI.http
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
@DotnetRedisCacheAPI_HostAddress = http://localhost:5127 | ||
|
||
GET {{DotnetRedisCacheAPI_HostAddress}}/weatherforecast/ | ||
Accept: application/json | ||
|
||
### |
15 changes: 15 additions & 0 deletions
15
DotnetRedisCacheAPI/DotnetRedisCacheAPI/Models/JsonPlaceholderDtos.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
namespace DotnetRedisCacheAPI.Models | ||
{ | ||
public class JsonPlaceholderDtos | ||
{ | ||
public record PostDto(int Id, int UserId, string Titel, string Body); | ||
public record CommentDto(int Id, int PostId, string Name, string Email, string Body); | ||
|
||
public record AlbumDto(int Id, int UserId, string Title); | ||
public record PhotoDto(int Id, int AlbumId, string Title, string Url, string ThumbnailUrl); | ||
public record TodoDto(int Id, int UserId, string Title, bool Completed); | ||
public record UserDto(int Id, string Name, string Username, string Email); | ||
|
||
|
||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
using DotnetRedisCacheAPI.Service; | ||
using Scalar.AspNetCore; | ||
|
||
var builder = WebApplication.CreateBuilder(args); | ||
|
||
// Add services to the container. | ||
|
||
builder.Services.AddControllers(); | ||
// Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi | ||
builder.Services.AddOpenApi(); | ||
|
||
|
||
builder.Services.AddTransient<IRedisService, RedisService>(); | ||
|
||
builder.Services.AddHttpClient(); | ||
|
||
|
||
builder.Services.AddTransient<IJsonPlaceholderService, JsonPlaceholderService>(); | ||
|
||
var app = builder.Build(); | ||
|
||
// Configure the HTTP request pipeline. | ||
if (app.Environment.IsDevelopment()) | ||
{ | ||
app.MapOpenApi(); | ||
app.MapScalarApiReference(); | ||
} | ||
|
||
app.UseHttpsRedirection(); | ||
|
||
app.UseAuthorization(); | ||
|
||
app.MapControllers(); | ||
|
||
app.Run(); |
25 changes: 25 additions & 0 deletions
25
DotnetRedisCacheAPI/DotnetRedisCacheAPI/Properties/launchSettings.json
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
{ | ||
"$schema": "https://json.schemastore.org/launchsettings.json", | ||
"profiles": { | ||
"http": { | ||
"commandName": "Project", | ||
"dotnetRunMessages": true, | ||
"launchBrowser": true, | ||
"launchUrl": "scalar/v1", | ||
"applicationUrl": "http://localhost:5127", | ||
"environmentVariables": { | ||
"ASPNETCORE_ENVIRONMENT": "Development" | ||
} | ||
}, | ||
"https": { | ||
"commandName": "Project", | ||
"dotnetRunMessages": true, | ||
"launchBrowser": true, | ||
"launchUrl": "scalar/v1", | ||
"applicationUrl": "https://localhost:7221;http://localhost:5127", | ||
"environmentVariables": { | ||
"ASPNETCORE_ENVIRONMENT": "Development" | ||
} | ||
} | ||
} | ||
} |
15 changes: 15 additions & 0 deletions
15
DotnetRedisCacheAPI/DotnetRedisCacheAPI/Service/IJsonPlaceholderService.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
using static DotnetRedisCacheAPI.Models.JsonPlaceholderDtos; | ||
|
||
namespace DotnetRedisCacheAPI.Service | ||
{ | ||
public interface IJsonPlaceholderService | ||
{ | ||
Task<IEnumerable<PostDto>> GetAllPosts(); | ||
Task<IEnumerable<CommentDto>> GetAllComments(); | ||
Task<IEnumerable<AlbumDto>> GetAllAlbums(); | ||
Task<IEnumerable<PhotoDto>> GetAllPhotos(); | ||
Task<IEnumerable<TodoDto>> GetAllTodos(); | ||
Task<IEnumerable<UserDto>> GetAllUsers(); | ||
|
||
} | ||
} |
9 changes: 9 additions & 0 deletions
9
DotnetRedisCacheAPI/DotnetRedisCacheAPI/Service/IRedisService.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
namespace DotnetRedisCacheAPI.Service | ||
{ | ||
public interface IRedisService | ||
{ | ||
|
||
Task<T> GetDataAsync<T>(string key); | ||
Task<bool> SetDataAsync<T>(string key, T value, DateTime expirationTime); | ||
} | ||
} |
91 changes: 91 additions & 0 deletions
91
DotnetRedisCacheAPI/DotnetRedisCacheAPI/Service/JsonPlaceholderService.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,91 @@ | ||
using static DotnetRedisCacheAPI.Models.JsonPlaceholderDtos; | ||
|
||
namespace DotnetRedisCacheAPI.Service | ||
{ | ||
public class JsonPlaceholderService : IJsonPlaceholderService | ||
{ | ||
private readonly HttpClient _httpClient; | ||
private readonly IRedisService _redisService; | ||
private readonly ILogger<JsonPlaceholderService> _logger; | ||
private const string BASE_URL = "https://jsonplaceholder.typicode.com"; | ||
private const int DEFAULT_CACHE_MINUTE = 5; | ||
|
||
|
||
public JsonPlaceholderService( | ||
|
||
HttpClient httpClient | ||
, IRedisService redisService | ||
, ILogger<JsonPlaceholderService> logger | ||
|
||
) | ||
{ | ||
_httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient)); | ||
_redisService = redisService ?? throw new ArgumentNullException(nameof(redisService)); | ||
_logger = logger ?? throw new ArgumentNullException(nameof(logger)); | ||
_httpClient.BaseAddress = new Uri(BASE_URL); | ||
} | ||
|
||
|
||
private async Task<IEnumerable<T>> GetCachedDataAsync<T>(string endpoint, string cacheKey, string entityName) | ||
{ | ||
try | ||
{ | ||
var cachedData = await _redisService.GetDataAsync<IEnumerable<T>>(cacheKey); | ||
if (cachedData != null) | ||
{ | ||
_logger.LogInformation($"{entityName} retrieved from cache "); | ||
return cachedData; | ||
} | ||
|
||
var data = await _httpClient.GetFromJsonAsync<IEnumerable<T>>(endpoint); | ||
if (data != null) | ||
{ | ||
await _redisService.SetDataAsync(cacheKey, data, DateTime.UtcNow.AddMinutes(DEFAULT_CACHE_MINUTE)); | ||
_logger.LogInformation($"{entityName} cached successfully "); | ||
return data; | ||
} | ||
_logger.LogWarning($" No {entityName} data received from API"); | ||
return Enumerable.Empty<T>(); | ||
|
||
|
||
} | ||
catch (Exception ex) | ||
{ | ||
_logger.LogError(ex, $"Error retrieving {entityName}: {ex.Message}"); | ||
throw; | ||
|
||
} | ||
} | ||
|
||
|
||
public Task<IEnumerable<PostDto>> GetAllPosts() => | ||
|
||
GetCachedDataAsync<PostDto>("/posts", "posts_all", "posts"); | ||
|
||
|
||
|
||
public Task<IEnumerable<CommentDto>> GetAllComments() => | ||
|
||
GetCachedDataAsync<CommentDto>("/comments", "comments_all", "Comments"); | ||
|
||
|
||
|
||
public Task<IEnumerable<AlbumDto>> GetAllAlbums() => | ||
GetCachedDataAsync<AlbumDto>("/albums", "albums_all", "Albums"); | ||
|
||
|
||
|
||
public Task<IEnumerable<PhotoDto>> GetAllPhotos() => | ||
GetCachedDataAsync<PhotoDto>("/photos", "photos_all", "Photos"); | ||
|
||
|
||
|
||
public Task<IEnumerable<TodoDto>> GetAllTodos() => | ||
GetCachedDataAsync<TodoDto>("/todos", "todos_all", "Todos"); | ||
|
||
|
||
public Task<IEnumerable<UserDto>> GetAllUsers() => | ||
GetCachedDataAsync<UserDto>("/users", "users_all", "Users"); | ||
|
||
} | ||
} |
29 changes: 29 additions & 0 deletions
29
DotnetRedisCacheAPI/DotnetRedisCacheAPI/Service/RedisService.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
| ||
using StackExchange.Redis; | ||
using System.Text.Json; | ||
|
||
namespace DotnetRedisCacheAPI.Service | ||
{ | ||
public class RedisService : IRedisService | ||
{ | ||
private readonly IDatabase _database; | ||
|
||
public RedisService() | ||
{ | ||
var redis = ConnectionMultiplexer.Connect("localhost:6379"); | ||
_database = redis.GetDatabase(); | ||
} | ||
|
||
public async Task<T> GetDataAsync<T>(string key) | ||
{ | ||
var value = await _database.StringGetAsync(key); | ||
return value.IsNull ? default : JsonSerializer.Deserialize<T>(value); | ||
} | ||
|
||
public async Task<bool> SetDataAsync<T>(string key, T value, DateTime expirationTime) | ||
{ | ||
var json = JsonSerializer.Serialize(value); | ||
return await _database.StringSetAsync(key, json, expirationTime - DateTime.Now); | ||
} | ||
} | ||
} |
8 changes: 8 additions & 0 deletions
8
DotnetRedisCacheAPI/DotnetRedisCacheAPI/appsettings.Development.json
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
{ | ||
"Logging": { | ||
"LogLevel": { | ||
"Default": "Information", | ||
"Microsoft.AspNetCore": "Warning" | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
{ | ||
"Logging": { | ||
"LogLevel": { | ||
"Default": "Information", | ||
"Microsoft.AspNetCore": "Warning" | ||
} | ||
}, | ||
"AllowedHosts": "*" | ||
} |