Skip to content

Commit

Permalink
Implemented Azure Redis Cache for weather data
Browse files Browse the repository at this point in the history
  • Loading branch information
Torkelsen committed Oct 21, 2024
1 parent 482eb81 commit d386dce
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
<PackageReference Include="Microsoft.Identity.Web.MicrosoftGraph" Version="3.1.0" />
<PackageReference Include="Microsoft.Identity.Web.UI" Version="3.1.0" />
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.21.0" />
<PackageReference Include="StackExchange.Redis" Version="2.8.16" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.7.3" />
<PackageReference Include="System.Net.Http" Version="4.3.4" />
</ItemGroup>
Expand Down
1 change: 1 addition & 0 deletions handlenett-backend/web-api/HandlenettAPI/Models/Weather.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,6 @@ public class Weather
{
public string Temperature { get; set; }
public Uri ImageUri { get; set; }
public DateTime LastUpdated { get; set; }
}
}
Original file line number Diff line number Diff line change
@@ -1,19 +1,43 @@
using HandlenettAPI.Models;
using Azure.Identity;
using HandlenettAPI.Models;
using Newtonsoft.Json.Linq;
using StackExchange.Redis;
using System.Text.Json;

namespace HandlenettAPI.Services
{
public class WeatherService
{
private readonly HttpClient _httpClient;
private readonly ConnectionMultiplexer _redis;

public WeatherService(HttpClient httpClient)
public WeatherService(HttpClient httpClient, IConfiguration config)
{
_httpClient = httpClient;
_httpClient.DefaultRequestHeaders.Add("User-Agent", "Miles Haugesund Handlenett/1.0 ([email protected])");
_redis = ConnectionMultiplexer.Connect(config.GetConnectionString("AzureRedisCache"));
}

public async Task<Weather> GetWeatherByCoordinatesAsync(double latitude, double longitude)
{
Weather? weather = null;

var cachedValue = GetCacheValue("Weather");
if (cachedValue != null)
{
weather = JsonSerializer.Deserialize<Weather>(cachedValue.ToString());
}

if (weather == null || weather.LastUpdated <= DateTime.UtcNow.AddHours(-1))
{
weather = await GetDataFromMet(latitude, longitude);
weather.LastUpdated = DateTime.UtcNow;
SetCacheValue("Weather", JsonSerializer.Serialize<Weather>(weather));
}
return weather;
}

private async Task<Weather> GetDataFromMet(double latitude, double longitude)
{
var returnModel = new Weather();
var url = $"https://api.met.no/weatherapi/locationforecast/2.0/compact?lat={latitude}&lon={longitude}";
Expand All @@ -27,16 +51,29 @@ public async Task<Weather> GetWeatherByCoordinatesAsync(double latitude, double

returnModel.Temperature = json["properties"]["timeseries"][0]["data"]["instant"]["details"]["air_temperature"].ToString();
var symbol = json["properties"]["timeseries"][0]["data"]["next_1_hours"]["summary"]["symbol_code"].ToString();

//TODO: add icons for displaying weather in web app
//returnModel.ImageUri = new Uri($"https://api.met.no/weatherapi/weathericon/2.0/?symbol={symbol}&content_type=image/png");
//https://github.com/metno/weathericons

return returnModel;
}
else
{
throw new Exception ("Unable to retrieve weather data from MET Norway.");
throw new Exception("Unable to retrieve weather data from MET Norway.");
}
}

private void SetCacheValue(string key, string value)
{
var db = _redis.GetDatabase();
db.StringSet(key, value);
}

private string? GetCacheValue(string key)
{
var db = _redis.GetDatabase();
return db.StringGet(key);
}
}
}

0 comments on commit d386dce

Please sign in to comment.