2013-09-30 14 views

Odpowiedz

8

try:

Set<byte[]> keys = RedisTemplate.getConnectionFactory().getConnection().keys("*".getBytes()); 

Iterator<byte[]> it = keys.iterator(); 

while(it.hasNext()){ 

    byte[] data = (byte[])it.next(); 

    System.out.println(new String(data, 0, data.length)); 
} 
3

Spróbuj redisTemplate.setKeySerializer(new StringRedisSerializer());

0

To nie działa, ale wydaje się nie poleca? Ponieważ nie możemy użyć polecenia Keys w produkcji. Zakładam, że RedisTemplate.getConnectionFactory().getConnection().keys wywołuje komendę redis Keys. Jakie są alternatywy?

0

Rozwiązanie może być jak ten

String pattern = "abc"+"*"; 
Set<String> keys = jedis.keys(pattern); 
for (String key : keys) { 
    jedis.keys(key); 
} 

Albo można użyć jedis.hscan() i ScanParams zamiast.

11

Po prostu skonsolidowałem odpowiedzi, które widzieliśmy tutaj.

Oto dwa sposoby uzyskiwania kluczy od Redis, kiedy używamy RedisTemplate.

1. Bezpośrednio z 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); 
} 

Uwaga: Należy mieć skonfigurowany redisTemplate z StringRedisSerializer w fasoli

Jeśli używasz Java konfiguracja fasola

redisTemplate.setDefaultSerializer(new StringRedisSerializer()); 

Jeśli używasz oparty spring.xml konfiguracja fasola

<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. Od 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(); 

Jeśli nie zamykać tego połączenia wprost, będziesz napotkasz na wyczerpaniu podstawową pulę połączeń jedis, jak podano w https://stackoverflow.com/a/36641934/3884173.

+0

Bardzo mi to pomogło, zasługuje na więcej awansów !! – varunkr

+0

To powinna być zaakceptowana odpowiedź. –

0

Używałem redisTemplate.keys(), ale nie działało. Więc użyłem jedis, zadziałało. Poniżej znajduje się kod, którego użyłem.

Jedis jedis = new Jedis("localhost", 6379); 
    Set<String> keys = jedis.keys("*".getBytes()); 
    for (String key : keys) { 
     // do something 
    } // for 
Powiązane problemy