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

网友投稿 915 2022-07-26


目录Spring RedisTemplate 批量获取值1、利用mGet2、利用PipeLinejava对Redis的批量操作RedisTemplate1、背景2、操作3、说明

Spring RedisTemplate 批量获取值

1、利用mGet

List keys = new ArrayList<>();

//初始keyEWfKFLQHNJs

List list = this.redisTemplate.opsForValue().multiGet(keys);

2、利用PipeLine

List list = this.redisTemplate.executePipelined(new RedisCallback() {

@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 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 execute(RedisCallback 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 : createRehttp://disConnectionProxy(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 keys = new ArrayList<>();

for (Book e : booklist) {

String key = generateKey.getKey(e);

keys.add(key);

}

List resultStr = template.opsForValue().multiGet(keys);

此方法还是比较好用,使用者注意封装。

RedisTemplate的Pipeline使用

1)方式一 : 基础方式

使用类:StringRedisTemplate使用方法

public executePipelined(RedisCallback> action) {...}

示例代码:批量获取value

List redisResult = redisTemplate.executePipelined(new RedisCallback() {

@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 executePipelined(final RedisCallback> action, final RedisSerializer> resultSerializer) {...}

示例代码:批量获取hash数据结构value

List redisResult = redisTemplate.executePipelined(

new RedisCallback() {

// 自定义序列化

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也进行了实现,见下会分解。


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:SpringBoot教程_创建第一个SpringBoot项目
下一篇:Java easyexcel使用教程之导出篇
相关文章

 发表评论

暂时没有评论,来抢沙发吧~