Introduction
Using pipelines helps send many commands to Redis at once, making it faster than sending commands one by one.
Using pipelines helps send many commands to Redis at once, making it faster than sending commands one by one.
redis-cli --pipe <<EOF SET key1 value1 SET key2 value2 EOF
redis> SET key1 value1 redis> SET key2 value2 redis> GET key1 redis> GET key2
redis-cli --pipe <<EOF SET key1 value1 SET key2 value2 GET key1 GET key2 EOF
Using a Redis client pipeline feature: pipe = redis_client.pipeline() pipe.set('key1', 'value1') pipe.set('key2', 'value2') pipe.execute()
This example shows setting and getting keys individually and then using a pipeline to do the same faster.
# Using redis-py client import redis r = redis.Redis() # Individual commands r.set('a', '1') r.set('b', '2') val_a = r.get('a') val_b = r.get('b') # Using pipeline pipe = r.pipeline() pipe.set('x', '10') pipe.set('y', '20') pipe.execute() val_x, val_y = r.get('x'), r.get('y') print(val_a.decode(), val_b.decode()) print(val_x.decode(), val_y.decode())
Pipelines reduce network delays by sending many commands at once.
Pipelines do not provide atomicity. Use MULTI/EXEC for atomic transactions.
Using pipelines can greatly improve performance in apps with many Redis calls.
Pipelines send multiple commands together to save time.
Individual commands wait for each reply, which is slower.
Use pipelines to speed up Redis operations when possible.
pipeline in Redis compared to sending individual commands?pipeline() method to create a pipeline object.start_pipeline(), beginPipeline(), or pipeline_start() are not valid methods in redis-py.pipe = redis_client.pipeline()
pipe.set('key1', 'value1')
pipe.set('key2', 'value2')
results = pipe.execute()
What will results contain after execution?set returns in RedisSET command returns the string "OK" on success.execute() returnexecute() method returns a list of replies from all commands in order, so two set commands return ["OK", "OK"].pipe = redis_client.pipeline()
pipe.set('key1', 'value1')
val = pipe.get('key1')
val.decode()
pipe.execute()
What is the likely cause of the error?set and get are queued in the pipeline and not executed until execute() is called.get resultget immediately (before execute()), it causes an error because the command hasn't run yet.get before executing the pipeline. -> Option Bset commands together, then execute once. -> Option DPass the test and this pattern moves unknown