Spring RedisTemplate批量获取值
Leon-Zheng 人气:0Spring RedisTemplate 批量获取值
1、利用mGet
List<String> keys = new ArrayList<>(); //初始keys List<YourObject> list = this.redisTemplate.opsForValue().multiGet(keys);
2、利用PipeLine
List<YourObject> list = this.redisTemplate.executePipelined(new RedisCallback<YourObject>() { @Override public YourObject doInRedis(RedisConnection connection) throws DataAccessException { StringRedisConnection conn = (StringRedisConnection)connection; for (String key : keys) { conn.get(key); } return null; } });
其实2者底层都是用到execute方法,multiGet在使用连接是没用到pipeline,一条命令直接传给Redis,Redis返回结果。而executePipelined实际上一条或多条命令,但是共用一个连接。
/** * Executes the given action object within a connection that can be exposed or not. Additionally, the connection can * be pipelined. Note the results of the pipeline are discarded (making it suitable for write-only scenarios). * * @param <T> return type * @param action callback object to execute * @param exposeConnection whether to enforce exposure of the native Redis Connection to callback code * @param pipeline whether to pipeline or not the connection for the execution * @return object returned by the action */ public <T> T execute(RedisCallback<T> action, boolean exposeConnection, boolean pipeline) { Assert.isTrue(initialized, "template not initialized; call afterPropertiesSet() before using it"); Assert.notNull(action, "Callback object must not be null"); RedisConnectionFactory factory = getConnectionFactory(); RedisConnection conn = null; try { if (enableTransactionSupport) { // only bind resources in case of potential transaction synchronization conn = RedisConnectionUtils.bindConnection(factory, enableTransactionSupport); } else { conn = RedisConnectionUtils.getConnection(factory); } boolean existingConnection = TransactionSynchronizationManager.hasResource(factory); RedisConnection connToUse = preProcessConnection(conn, existingConnection); boolean pipelineStatus = connToUse.isPipelined(); if (pipeline && !pipelineStatus) { //开启管道 connToUse.openPipeline(); } RedisConnection connToExpose = (exposeConnection ? connToUse : createRedisConnectionProxy(connToUse)); T result = action.doInRedis(connToExpose); if (pipeline && !pipelineStatus) {// 关闭管道 connToUse.closePipeline(); } // TODO: any other connection processing? return postProcessResult(result, connToUse, existingConnection); } finally { if (!enableTransactionSupport) { RedisConnectionUtils.releaseConnection(conn, factory); } } }
还有一点,就是查询返回的结果,和键的顺序是一一对应的,如果没查到,会返回null值。
Java对Redis的批量操作RedisTemplate
1、背景
需求:一次性获取redis缓存中多个key的value
潜在隐患:循环key,获取value,可能会造成连接池的连接数增多,连接的创建和摧毁,消耗性能
解决方法:根据项目中的缓存数据结构的实际情况,数据结构为string类型的,使用RedisTemplate的multiGet方法;数据结构为hash,使用Pipeline(管道),组合命令,批量操作redis。
2、操作
RedisTemplate的multiGet的操作
- 针对数据结构为String类型
- 示例代码
List<String> keys = new ArrayList<>(); for (Book e : booklist) { String key = generateKey.getKey(e); keys.add(key); } List<Serializable> resultStr = template.opsForValue().multiGet(keys);
此方法还是比较好用,使用者注意封装。
RedisTemplate的Pipeline使用
1)方式一 : 基础方式
- 使用类:StringRedisTemplate
- 使用方法
public executePipelined(RedisCallback<?> action) {...}
- 示例代码:批量获取value
List<Object> redisResult = redisTemplate.executePipelined(new RedisCallback<String>() { @Override public String doInRedis(RedisConnection redisConnection) throws DataAccessException { for (BooK e : booklist) { StringRedisConnection stringRedisConnection =(StringRedisConnection)redisConnection; stringRedisConnection.get(e.getId()); } return null; } });
方法二 : 使用自定义序列化方法
- 使用类:RedisTemplate
- 使用方法
public List<Object> executePipelined(final RedisCallback<?> action, final RedisSerializer<?> resultSerializer) {...}
- 示例代码:批量获取hash数据结构value
List<Object> redisResult = redisTemplate.executePipelined( new RedisCallback<String>() { // 自定义序列化 RedisSerializer keyS = redisTemplate.getKeySerializer(); @Override public String doInRedis(RedisConnection redisConnection) throws DataAccessException { for (BooK e : booklist) { redisConnection.hGet(keyS.serialize(e.getName()), keyS.serialize(e.getAuthor())); } return null; } }, redisTemplate.getValueSerializer()); // 自定义序列化
3、说明
本文简单的举了关于RedisTemplate的两个例子,但大家千万别以为只是批量取值的时候会用到,PipeLine其实是用来批量发送命令操作Redis。后来用Jedis也进行了实现,见下会分解。
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。
加载全部内容