The new concept on a better .NET caching abtraction is presented by Marc Gravell's Distributed Cache Demo. This weather app is an example to show how to reuse the extension methods from Distributed Cache Demo code to cache weather forecast reports, with both stateless and stateful options.
Pre-requisites for running the Weather API app
- .NET 8 or above. Download
- Sign-up for an Azure Subscription if you don't have one yet. Start free
- Setup Git command line
-
Create an Azure Cache for Redis. Follow instructions at here.
NOTE: You can choose the tier (Basic, Standard, Premium, Enterprise) for the Redis Cache to create. Creating Enterprise SKU will take only ~5min, while other SKUs may take longer to be created.
-
Open command prompt. Change directory to a folder location you want to run this sample code. Fork this sample code.
-
Download the forked sample code in your own Github repo:
git clone https://github.com/<your_github_username>/WeatherAPI-DistributedCache.git
-
Make sure you are in the folder directory containing the .csproj file. Initialize user-secret for this project:
dotnet user-secrets init
-
Navigate to Azure Portal. Browse to the Azure Cache for Redis instance you created. Go to Access Keys tab, obtain the primary connection string.
-
Set user secret to your project:
dotnet user-secrets set "ConnectionStrings:MyRedisConStr" "Your_Redis_Connection_String"
-
Run the app:
dotnet build set ASPNETCORE_ENVIRONMENT=Development dotnet run
-
Launch the Web App locally following the output in command prompt. You will be able to see the weather forecast for the next week. Refreshing the browser will not change the result because the generated weather forecast is cached! The screenshot below shows invoking the URL to index action returns next week's weather forecast in JSON format.
-
View more weather forecast by appending /GetFuture/{numWeeks}/{numMonthsFromNow} to the URL. For example, https://localhost:55215/GetFuture/1/2 will show the weather forecast 2 months and 1 week from today. The screenshot below shows getting the future weather 2 months and 1 week from now.
-
Go to Azure portal, browse to your Azure Cache for Redis instance. Launch the Console tool per screenshot below.
-
Use KEYS * and HGETALL <your_cached_value_key> commands to view the cached weather forecast.
The azd support deploys this web application to an Azure Container App instance. Prerequisites:
- Azure subscription. Start free
- .NET 8 or above. Download
- Docker. Get docker
- Azure Developer CLI. Install
- Open a command prompt
- Change directory to the project folder where azure.yaml file is located
- Run:
azd up
- Follow command prompt to enter environment name and select subscription
- This will create all the resources needed to run the sample:
- Azure Container App instance and environment
- Azure Container Registry
- Azure Cache for Redis
- Azure Key Vault
- To clean up the environment, run
azd down