springboot Redistemplate的execute和 executePipelined


springboot 的 RedisTemplate 的 execute 和 executePipelined 功能的區別

1.execute

以下是 springboot 官網原文:

Redis provides support for transactions through the multiexec, and discard commands. These operations are available on RedisTemplate, however RedisTemplate is not guaranteed to execute all operations in the transaction using the same connection.

Spring Data Redis provides the SessionCallback interface for use when multiple operations need to be performed with the same connection, as when using Redis transactions. For example:

```

 //execute a transaction
List<Object> txResults = redisTemplate.execute(new SessionCallback<List<Object>>() { public List<Object> execute(RedisOperations operations) throws DataAccessException { operations.multi(); operations.opsForSet().add("key", "value1"); // This will contain the results of all ops in the transaction return operations.exec(); } });

 ```

翻譯下來就是:

Redis 通過multi, exec, discard 操作提供事務支持. RedisTemplate 也同樣支持這些操作, 然而 RedisTemplate 不保證在同一個連接中執行事務中的所有操作.

當使用 redis 的事務的時候,  Spring Data Redis 提供 SessionCallback 的接口支持多個操作的執行都在同一個連接中.

 

2.Pipeline

 

Redis provides support for pipelining, which involves sending multiple commands to the server without waiting for the replies and then reading the replies in a single step. Pipelining can improve performance when you need to send several commands in a row, such as adding many elements to the same List.

Spring Data Redis provides several RedisTemplate methods for executing commands in a pipeline. If you don't care about the results of the pipelined operations, you can use the standard execute method, passing true for the pipeline argument. The executePipelined methods will execute the provided RedisCallback or SessionCallback in a pipeline and return the results. For example:

 

Redis 提供 pipelining(管道) 的支持,  它可以發送多條指令到 redis服務端 而不用等待服務端的回復 並且 讀取服務端的回復在一步操作中. 當你需要連續發送多條命令的時候 Pipelining(管道) 可以改善性能, such as 添加多個元素到同一個list中.

Spring Data Redis 提供幾個 RedisTemplate 的方法支持在一個 pipeline(管道) 中執行多個指令.如果不關注管道操作的結果, 可以使用標准的execute方法, 傳遞true 的pipeline參數.

executePipelined 方法會執行 RedisCallback or SessionCallback 的回調方法以返回結果.

```

//pop a specified number of items from a queue
List<Object> results = stringRedisTemplate.executePipelined(new RedisCallback<Object>() { public Object doInRedis(RedisConnection connection) throws DataAccessException { StringRedisConnection stringRedisConn = (StringRedisConnection)connection; for(int i=0; i< batchSize; i++) { stringRedisConn.rPop("myqueue"); } return null; } });

```

在redis官網中: ( 官網地址: https://redis.io/topics/pipelining )

從  It's not just a matter of RTT 這一段開始, pipeline不僅僅是不用等待回復時間(RTT)就可以持續的發送指令. 並且使用 pipeline的時候, redis用一個read()操作讀取多個指令,並且 通過一個 write() 傳遞多個結果.最終的結果, 使用 pipeline 的效率甚至能相當於不使用pipeline的 10 倍.

(來張官網的圖)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM