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,可能會造成連接池的連接數(shù)增多,連接的創(chuàng)建和摧毀,消耗性能
解決方法:根據(jù)項目中的緩存數(shù)據(jù)結構的實際情況,數(shù)據(jù)結構為string類型的,使用RedisTemplate的multiGet方法;數(shù)據(jù)結構為hash,使用Pipeline(管道),組合命令,批量操作redis。
2、操作
RedisTemplate的multiGet的操作
- 針對數(shù)據(jù)結構為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數(shù)據(jù)結構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也進行了實現(xiàn),見下會分解。
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
基于springboot微信公眾號開發(fā)(微信自動回復)
這篇文章主要介紹了基于springboot微信公眾號開發(fā)(微信自動回復),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-11-11
SpringBoot連接MYSQL數(shù)據(jù)庫并使用JPA進行操作
今天給大家介紹一下如何SpringBoot中連接Mysql數(shù)據(jù)庫,并使用JPA進行數(shù)據(jù)庫的相關操作。2017-04-04

