0
点赞
收藏
分享

微信扫一扫

Spring RedisTemplate 批量获取值的2种方式


1、利用mGet

1. List<String> keys = new ArrayList<>();
2. //初始keys
3. List<YourObject> list = this.redisTemplate.opsForValue().multiGet(keys);

2、利用PipeLine

1. List<YourObject> list = this.redisTemplate.executePipelined(new RedisCallback<YourObject>() {
2. @Override
3. public YourObject doInRedis(RedisConnection connection) throws DataAccessException {
4. StringRedisConnection conn = (StringRedisConnection)connection;
5. for (String key : keys) {
6. conn.get(key);
7. }
8. return null;
9. }
10. });

其实2者底层都是用到execute方法,multiGet在使用连接是没用到pipeline,一条命令直接传给Redis,Redis返回结果。而executePipelined实际上一条或多条命令,但是共用一个连接。

1. /**
2. * Executes the given action object within a connection that can be exposed or not. Additionally, the connection can
3. * be pipelined. Note the results of the pipeline are discarded (making it suitable for write-only scenarios).
4. *
5. * @param <T> return type
6. * @param action callback object to execute
7. * @param exposeConnection whether to enforce exposure of the native Redis Connection to callback code
8. * @param pipeline whether to pipeline or not the connection for the execution
9. * @return object returned by the action
10. */
11. public <T> T execute(RedisCallback<T> action, boolean exposeConnection, boolean pipeline) {
12. Assert.isTrue(initialized, "template not initialized; call afterPropertiesSet() before using it");
13. Assert.notNull(action, "Callback object must not be null");
14.  
15. RedisConnectionFactory factory = getConnectionFactory();
16. RedisConnection conn = null;
17. try {
18.  
19. if (enableTransactionSupport) {
20. // only bind resources in case of potential transaction synchronization
21. conn = RedisConnectionUtils.bindConnection(factory, enableTransactionSupport);
22. } else {
23. conn = RedisConnectionUtils.getConnection(factory);
24. }
25.  
26. boolean existingConnection = TransactionSynchronizationManager.hasResource(factory);
27.  
28. RedisConnection connToUse = preProcessConnection(conn, existingConnection);
29.  
30. boolean pipelineStatus = connToUse.isPipelined();
31. if (pipeline && !pipelineStatus) { //开启管道
32. connToUse.openPipeline();
33. }
34.  
35. RedisConnection connToExpose = (exposeConnection ? connToUse : createRedisConnectionProxy(connToUse));
36. T result = action.doInRedis(connToExpose);
37.  
38. if (pipeline && !pipelineStatus) {// 关闭管道
39. connToUse.closePipeline();
40. }
41.  
42. // TODO: any other connection processing?
43. return postProcessResult(result, connToUse, existingConnection);
44. } finally {
45.  
46. if (!enableTransactionSupport) {
47. RedisConnectionUtils.releaseConnection(conn, factory);
48. }
49. }
50. }

还有一点,就是查询返回的结果,和键的顺序是一一对应的,如果没查到,会返回null值。

举报

相关推荐

0 条评论