forked from itsecd/cloud-development
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
67 lines (53 loc) · 1.86 KB
/
Program.cs
File metadata and controls
67 lines (53 loc) · 1.86 KB
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
using System.Text.Json;
using Microsoft.Extensions.Caching.Distributed;
using VehicleApi.Models;
using VehicleApi.Services;
var builder = WebApplication.CreateBuilder(args);
// Add ServiceDefaults (OpenTelemetry, health checks, service discovery)
builder.AddServiceDefaults();
// Add Redis distributed caching
builder.AddRedisDistributedCache("cache");
// Add CORS for Blazor client
builder.Services.AddCors(options =>
{
options.AddDefaultPolicy(policy =>
{
policy.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
});
});
var app = builder.Build();
// Enable CORS
app.UseCors();
// Map health checks
app.MapDefaultEndpoints();
// API endpoint for vehicle data
app.MapGet("/api/vehicles", async (int id, IDistributedCache cache, ILogger<Program> logger) =>
{
if (id <= 0)
{
logger.LogWarning("Invalid vehicle ID {Id} requested", id);
return Results.BadRequest("ID must be greater than 0");
}
var cacheKey = $"vehicle:{id}";
var cachedData = await cache.GetAsync(cacheKey);
if (cachedData != null)
{
logger.LogInformation("Cache hit for vehicle ID {Id}", id);
var vehicle = JsonSerializer.Deserialize<Vehicle>(cachedData);
logger.LogInformation("Returning cached vehicle: {@Vehicle}", vehicle);
return Results.Ok(vehicle);
}
logger.LogInformation("Cache miss for vehicle ID {Id}", id);
var generated = VehicleGenerator.Generate(id);
logger.LogInformation("Generated new vehicle: {@Vehicle}", generated);
var serialized = JsonSerializer.SerializeToUtf8Bytes(generated);
await cache.SetAsync(cacheKey, serialized, new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10)
});
logger.LogInformation("Vehicle {Id} cached for 10 minutes", id);
return Results.Ok(generated);
});
app.Run();