Skip to content

Latest commit

 

History

History
83 lines (67 loc) · 2.43 KB

CACHING_EXAMPLE.md

File metadata and controls

83 lines (67 loc) · 2.43 KB

Caching

Simple API caching example with Redis! This repository is based on the video Caching API Responses with Redis. For further information on caching, check out these videos as well:

Prerequisites

Installing this application

Clone the repository to your computer:

git clone https://github.com/redis-developer/redis-caching-api-responses

Install dependencies:

npm install 

Add the Open Weather Map API Key to your Environment Variables:

export WEATHER_API_KEY=<your api key>

Database Preparation

Ensure you have Redis installed and running.

For Docker:

$ docker run -p 6379:6379 --name redis6 -d redis:6 

caching_example.js

This file contains logic to demonstrate caching entries from a weather service API. You will need a free API key of your own to run this demonstration. You can get your own API key by following the instructions at the Open WeatherMap API site. The getWeather() function retrieves a JSON object containing real-time meteorological information on a given city. This example uses Oakland, but you can use whichever city you like.

Ensure Redis is running, then run the api.js file once. Since there is no cache entry, the code will retrieve the data from the Open Weather Map API.

$ node api.js
{
  coord: { lon: -83.4, lat: 42.67 },
  weather: [
    {
      id: 803,
      main: 'Clouds',
      description: 'broken clouds',
      icon: '04d'
    }
  ],
  ...
  source: 'API',
  responseTime: '180ms'
}

The code will have placed a copy of the entry in the Redis cache, so the next function call will return data from the cache. Note that the cached entry has a TTL (Time To Live) of one hour. Weather can change frequently, so an hour should provide a reasonable approximation of the current conditions. After an hour, the cache entry will be removed automatically, and a new cache entry will need to be stored. This ensures fresh, relevant data.

$ node api.js
{
  coord: { lon: -83.4, lat: 42.67 },
  weather: [
    {
      id: 803,
      main: 'Clouds',
      description: 'broken clouds',
      icon: '04d'
    }
  ],
  ...
  source: 'cache',
  responseTime: '9ms'
}