Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for How to use ConfigCat with Redis
Chavez Harris
Chavez Harris

Posted on • Originally published atconfigcat.com

How to use ConfigCat with Redis

Ever since the dawn of feature releases, feature flags have become the de facto standard for managing and controlling features in software applications. Many software development methodologies these days such as agile, are heavily focused on releasing continuous updates and features. In addition, a few companies have based their entire business around serving clients a cloud-based feature flagging solution. But in limited bandwidth situations or when you need to optimize the performance of your client-facing applications making API requests may not be ideal. This can be handled by implementing a process called caching with the help of a popular tool calledRedis.

What are feature flags?

A feature flag can be described as a light switch for features. It holds a boolean value, that when set to true, the feature it controls can be displayed to the user and otherwise hidden.

The awesome thing about feature flagging is that it can be applied to a wide range ofprogramming languages and frameworks. And because of its flexible nature, it can be used alongside other technologies. Let's look at how it can be implemented with aRedis cache to see how it works.

Pre-requisites

To help you follow through with me, I've created a Node.js sample app that you can clone from the followinglink. Later on, we'll cover how to set it up.

Adding a feature flag

1. To get started, sign up for afree ConfigCat account.

2. In your dashboard, create a feature flag with the following information:

Image description

Creating the Redis cache client

3. From thestarter-code branch, open the file calledconfigcat-redis-cache.js and add the following functions:

// ...functionconfigcatRedisCache(redisClientOptions){this.isRedisAvailable=false;this.cacheClient=redis.createClient(redisClientOptions);this.cacheClient.connect();this.cacheClient.on("connect",()=>{console.log("Connected to Redis");this.isRedisAvailable=true;});this.cacheClient.on("error",(error)=>{console.log(`Redis error:${error}`);this.isRedisAvailable=false;});this.lastCacheItems={};}configcatRedisCache.prototype.get=asyncfunction(key){if(!this.isRedisAvailable){returnthis.lastCacheItems[key];}try{constgetAsync=util.promisify(this.cacheClient.get).bind(this.cacheClient);returnJSON.parse(awaitgetAsync(key));}catch(error){console.error(`Cache read failed! \n${error}`);returnthis.lastCacheItems[key];}};configcatRedisCache.prototype.set=asyncfunction(key,item){this.lastCacheItems[key]=item;try{constsetAsync=util.promisify(this.cacheClient.set).bind(this.cacheClient);awaitsetAsync(key,JSON.stringify(item));}catch(error){console.error(`Cache write failed! \n${error}`);}};// ...
Enter fullscreen modeExit fullscreen mode

Here's what each function does:

  • configcatRedisCache - Takes the client options as its parameter and sets up a connection to the docker Redis instance.

  • configcatRedisCache.prototype.get - Uses the providedkey to obtain the cached item from Redis.

  • configcatRedisCache.prototype.set - Takes thekey anditem as parameters. Puts theitem into the redis cache that can be later accessed using thekey.

4. Open theindex.js file and add the following code:

// ...constredisOptions={host:"localhost",port:6379};constconfigCatClient=configcat.getClient("0yDbCLmNK0qIUakB2LFJDA/u0Z5j4oDjkuHKOVJkIo9Dw",configcat.PollingMode.AutoPoll,{cache:configcatRedisCache(redisOptions)});setInterval(()=>{configCatClient.getValueAsync("isMyAwesomeFeatureEnabled",false).then(value=>{console.log(`${newDate().toTimeString()} isMyAwesomeFeatureEnabled:${value}`);});},5000);
Enter fullscreen modeExit fullscreen mode

Here's what the code is doing:

  • The configuration required to establish a connection to the Redis docker instance was saved to theredisOptions variable.

  • That variable was then used in theconfigcat.getClient method passed as an argument to set up thecache property.

  • ThesetInterval function runs every 5 seconds to fetch the value of the feature flag, but instead of reaching out toConfigCat, it obtains the value from the Redis cache and logs the result with the date to the console.

You can find the complete code for theindex.js filehere. If you're curious about learning more about using a custom cache withConfigCat as we did, refer tothis documentation.

With the code in place, let's look at how we can run the sample app to ensure it works.

Running the sample app

1. Clone theGitHub repository

2. Run the following commands to install the required node packages:

npminstall
Enter fullscreen modeExit fullscreen mode

Theconfigcat-node andredis npm packages will also be installed using this command. Theconfigcat-node package will be used as a client to connect to and pull the feature flag status from yourConfigCat dashboard.redis will be used similarly and would connect to a local docker instance of Redis.

3. Using docker, pull the latest Redis docker image and run the container:

docker pull redis
Enter fullscreen modeExit fullscreen mode
docker run--name container-redis-p 6379:6379-d redis
Enter fullscreen modeExit fullscreen mode

4. Start the node application with the following command:

npm start
Enter fullscreen modeExit fullscreen mode

You should see the following output logged to your terminal every 5 seconds:

> configcat-with-redis-sample@1.0.0 start> node index.jsConnected to Redis17:56:55 GMT-0300(French Guiana Time) isMyAwesomeFeatureEnabled:false17:57:00 GMT-0300(French Guiana Time) isMyAwesomeFeatureEnabled:false17:57:05 GMT-0300(French Guiana Time) isMyAwesomeFeatureEnabled:false17:57:10 GMT-0300(French Guiana Time) isMyAwesomeFeatureEnabled:false17:57:15 GMT-0300(French Guiana Time) isMyAwesomeFeatureEnabled:false17:57:20 GMT-0300(French Guiana Time) isMyAwesomeFeatureEnabled:false
Enter fullscreen modeExit fullscreen mode

Toggling on or off the feature flag within yourConfigCat dashboard will force the cache to refresh. As a result, The new value will be pulled fromConfigCat to replace the existing value in the cache.

Final thoughts

If you're planning on cutting back or saving bandwidth utilization and optimizing for better performance on the client side then a caching solution like Redis can help. And, as we've seen from the code examples, Redis integrates quite easily withConfigCat. With a caching solution in place, you can supercharge the way you do standard feature releases, canary deployments, and A/B testing. Besides Node.js, ConfigCat also supportsmany languages and frameworks and providesSDKs for easy configuration.

Stay updated

For more posts like this and other announcements, follow ConfigCat onTwitter,Facebook,LinkedIn, andGitHub.

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Inspiration does exist, but it must find you writing code.
  • Location
    Georgetown, Guyana
  • Work
    Software Engineer
  • Joined

More fromChavez Harris

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp