如何使用Redis模板从Redis获取所有密钥

编程入门 行业动态 更新时间:2024-10-25 06:31:21
本文介绍了如何使用Redis模板从Redis获取所有密钥的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我一直困扰这个问题很长时间,我想使用Redis模板从Redis获取密钥. 我尝试过this.redistemplate.keys("*"); 但这什么也没得到.即使使用该模式也不起作用.

I have been stuck with this problem with quite some time.I want to get keys from redis using redis template. I tried this.redistemplate.keys("*"); but this doesn't fetch anything. Even with the pattern it doesn't work.

请问什么是最好的解决方案.

Can you please advise on what is the best solution to this.

推荐答案

我刚刚合并了答案,我们已经在这里看到了.

I just consolidated the answers, we have seen here.

当我们使用RedisTemplate时,有两种从Redis获取密钥的方法.

Here are the two ways of getting keys from Redis, when we use RedisTemplate.

1.直接来自RedisTemplate

Set<String> redisKeys = template.keys("samplekey*")); // Store the keys in a List List<String> keysList = new ArrayList<>(); Iterator<String> it = redisKeys.iterator(); while (it.hasNext()) { String data = it.next(); keysList.add(data); }

注意:您应该在bean

Note: You should have configured redisTemplate with StringRedisSerializer in your bean

如果您使用基于Java的bean配置

redisTemplate.setDefaultSerializer(new StringRedisSerializer());

如果您使用基于spring.xml的bean配置

<bean id="stringRedisSerializer" class="org.springframework.data.redis.serializer.StringRedisSerializer"/> <!-- redis template definition --> <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate" p:connection-factory-ref="jedisConnectionFactory" p:keySerializer-ref="stringRedisSerializer" />

2.来自JedisConnectionFactory

RedisConnection redisConnection = template.getConnectionFactory().getConnection(); Set<byte[]> redisKeys = redisConnection.keys("samplekey*".getBytes()); List<String> keysList = new ArrayList<>(); Iterator<byte[]> it = redisKeys.iterator(); while (it.hasNext()) { byte[] data = (byte[]) it.next(); keysList.add(new String(data, 0, data.length)); } redisConnection.close();

如果您未明确关闭此连接,则会耗尽基础jedis连接池,如 stackoverflow/a/36641934/3884173 .

If you don't close this connection explicitly, you will run into an exhaustion of the underlying jedis connection pool as said in stackoverflow/a/36641934/3884173.

更多推荐

如何使用Redis模板从Redis获取所有密钥

本文发布于:2023-11-17 08:12:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1609424.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:密钥   如何使用   模板   Redis

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!