Spring RedisTemplate 批量獲取值的2種方式小結
Spring 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
潛在隱患:循環(huán)key,獲取value,可能會造成連接池的連接數增多,連接的創(chuàng)建和摧毀,消耗性能
解決方法:根據項目中的緩存數據結構的實際情況,數據結構為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其實是用來批量發(fā)送命令操作Redis。后來用Jedis也進行了實現,見下會分解。
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Swagger2不被SpringSecurity框架攔截的配置及說明
這篇文章主要介紹了Swagger2不被SpringSecurity框架攔截的配置及說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-03-03Spring實戰(zhàn)之使用TransactionProxyFactoryBean實現聲明式事務操作示例
這篇文章主要介紹了Spring實戰(zhàn)之使用TransactionProxyFactoryBean實現聲明式事務操作,結合實例形式分析了spring使用TransactionProxyFactoryBean實現聲明式事務相關配置、接口設置與使用技巧,需要的朋友可以參考下2020-01-01