Dragonfly Cloud is now available in the AWS Marketplace - learn more

Question: How to Close Redis Connection?

Answer

Closing a Redis connection depends on the programming language and client library you are using. Here, I'll show examples of closing connections in popular languages like Python, Node.js, and Ruby.

Python (Using redis-py)

To close a Redis connection using the redis-py library, you should call the close() method followed by the wait_closed() coroutine function if using an asynchronous connection, or simply the close() method for synchronous connections.

import redis r = redis.Redis(host='localhost', port=6379) # perform operations r.close()

For async connections:

import aioredis async def main(): r = await aioredis.create_redis_pool('redis://localhost') # perform operations r.close() await r.wait_closed() asyncio.run(main())

Node.js (Using ioredis)

To close a Redis connection using the ioredis library, you should call the disconnect() method.

const Redis = require('ioredis'); const redis = new Redis({ host: 'localhost', port: 6379, }); // perform operations redis.disconnect();

Ruby (Using redis-rb)

To close a Redis connection using the redis-rb library, you should call the disconnect! method.

require 'redis' redis = Redis.new(host: 'localhost', port: 6379) # perform operations redis.disconnect!

Remember to close the connection after you're done with all the required operations to ensure resources are released properly.

Was this content helpful?

White Paper

Free System Design on AWS E-Book

Download this early release of O'Reilly's latest cloud infrastructure e-book: System Design on AWS.

Free System Design on AWS E-Book

Switch & save up to 80% 

Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement. Instantly experience up to a 25X boost in performance and 80% reduction in cost