Cantumkan Semua Tombol Redis yang Tersedia

Java Top

Saya baru saja mengumumkan kursus Learn Spring baru , yang berfokus pada dasar-dasar Spring 5 dan Spring Boot 2:

>> LIHAT KURSUSnya

1. Ikhtisar

Koleksi adalah blok bangunan penting yang biasanya terlihat di hampir semua aplikasi modern. Jadi, tidak mengherankan jika Redis menawarkan berbagai struktur data populer seperti daftar, kumpulan, hash, dan kumpulan yang diurutkan untuk kita gunakan.

Dalam tutorial ini, kita akan belajar bagaimana kita dapat secara efektif membaca semua kunci Redis yang tersedia yang cocok dengan pola tertentu.

2. Jelajahi Koleksi

Bayangkan bahwa aplikasi kita menggunakan Redis untuk menyimpan informasi tentang bola yang digunakan dalam berbagai olahraga. Kami seharusnya dapat melihat informasi tentang setiap bola yang tersedia dari koleksi Redis. Untuk mempermudah, kami akan membatasi kumpulan data kami menjadi hanya tiga bola:

  • Bola kriket dengan berat 160 g
  • Sepak bola dengan berat 450 g
  • Bola voli dengan berat 270 g

Seperti biasa, pertama-tama mari kita bersihkan dasar-dasar kita dengan mengerjakan pendekatan naif untuk menjelajahi koleksi Redis.

3. Pendekatan Naif Menggunakan redis-cli

Sebelum kita mulai menulis kode Java untuk menjelajahi koleksi, kita harus memiliki gagasan yang baik tentang bagaimana kita akan melakukannya menggunakan antarmuka redis-cli . Mari kita asumsikan bahwa instance Redis tersedia di 127.0.0.1 pada port 6379 , bagi kita untuk menjelajahi setiap jenis koleksi dengan antarmuka baris perintah.

3.1. Daftar Tertaut

Pertama, mari simpan kumpulan data kita dalam daftar tertaut Redis bernama bola dalam format sports-name _ ball-weight dengan bantuan perintah rpush :

% redis-cli -h 127.0.0.1 -p 6379 127.0.0.1:6379> RPUSH balls "cricket_160" (integer) 1 127.0.0.1:6379> RPUSH balls "football_450" (integer) 2 127.0.0.1:6379> RPUSH balls "volleyball_270" (integer) 3

Kita dapat melihat bahwa penyisipan yang berhasil ke dalam daftar menghasilkan panjang daftar yang baru . Namun, dalam banyak kasus, kami tidak dapat melihat aktivitas penyisipan data. Hasilnya, kita bisa mengetahui panjang dari linked list menggunakan perintah llen :

127.0.0.1:6379> llen balls (integer) 3

Saat kita sudah mengetahui panjang daftarnya, lebih mudah menggunakan perintah lrange untuk mengambil seluruh kumpulan data dengan mudah:

127.0.0.1:6379> lrange balls 0 2 1) "cricket_160" 2) "football_450" 3) "volleyball_270"

3.2. Set

Selanjutnya, mari kita lihat bagaimana kita dapat menjelajahi kumpulan data saat kami memutuskan untuk menyimpannya dalam kumpulan Redis. Untuk melakukannya, pertama-tama kita perlu mengisi kumpulan data dalam set Redis bernama balls menggunakan perintah sadd :

127.0.0.1:6379> sadd balls "cricket_160" "football_450" "volleyball_270" "cricket_160" (integer) 3

Ups! Kami memiliki nilai duplikat dalam perintah kami. Tapi, karena kami menambahkan nilai ke satu set, kami tidak perlu khawatir tentang duplikat. Tentu saja, kita dapat melihat jumlah item yang ditambahkan dari nilai respon keluaran.

Sekarang, kita dapat memanfaatkan perintah smembers untuk melihat semua anggota set :

127.0.0.1:6379> smembers balls 1) "volleyball_270" 2) "cricket_160" 3) "football_450"

3.3. Hash

Sekarang, mari gunakan struktur data hash Redis untuk menyimpan kumpulan data kita dalam kunci hash bernama bola sehingga bidang hash adalah nama olahraga dan nilai bidang adalah berat bola. Kita bisa melakukan ini dengan bantuan perintah hmset :

127.0.0.1:6379> hmset balls cricket 160 football 450 volleyball 270 OK

Untuk melihat informasi yang disimpan di hash kita, kita bisa menggunakan perintah hgetall :

127.0.0.1:6379> hgetall balls 1) "cricket" 2) "160" 3) "football" 4) "450" 5) "volleyball" 6) "270"

3.4. Set yang Diurutkan

Selain nilai anggota yang unik, set yang diurutkan memungkinkan kita untuk menyimpan skor di sebelahnya. Nah, dalam kasus penggunaan kami, kami dapat menggunakan nama olahraga sebagai nilai anggota dan berat bola sebagai skor. Mari gunakan perintah zadd untuk menyimpan dataset kita:

127.0.0.1:6379> zadd balls 160 cricket 450 football 270 volleyball (integer) 3

Sekarang, pertama-tama kita dapat menggunakan perintah zcard untuk menemukan panjang set yang diurutkan, diikuti dengan perintah zrange untuk menjelajahi set lengkap :

127.0.0.1:6379> zcard balls (integer) 3 127.0.0.1:6379> zrange balls 0 2 1) "cricket" 2) "volleyball" 3) "football"

3.5. String

Kita juga dapat melihat string nilai kunci biasa sebagai kumpulan item yang dangkal . Mari pertama-tama mengisi dataset kita menggunakan perintah mset :

127.0.0.1:6379> mset balls:cricket 160 balls:football 450 balls:volleyball 270 OK

Kita harus mencatat bahwa kita menambahkan awalan “balls: sehingga kita dapat mengidentifikasi kunci-kunci ini dari kunci lainnya yang mungkin ada di database Redis kita. Selain itu, strategi penamaan ini memungkinkan kita menggunakan perintah keys untuk menjelajahi dataset kita dengan bantuan pencocokan pola awalan:

127.0.0.1:6379> keys balls* 1) "balls:cricket" 2) "balls:volleyball" 3) "balls:football"

4. Implementasi Java Naif

Sekarang kita telah mengembangkan ide dasar tentang perintah Redis yang relevan yang dapat kita gunakan untuk menjelajahi koleksi jenis yang berbeda, inilah saatnya kita mengotori tangan kita dengan kode.

4.1. Ketergantungan Maven

Di bagian ini, kita akan menggunakan pustaka klien Jedis untuk Redis dalam implementasi kita:

 redis.clients jedis 3.2.0 

4.2. Klien Redis

The Jedis library comes with the Redis-CLI name-alike methods. However, it's recommended that we create a wrapper Redis client, which will internally invoke Jedis function calls.

Whenever we're working with Jedis library, we must keep in mind that a single Jedis instance is not thread-safe. Therefore, to get a Jedis resource in our application, we can make use of JedisPool, which is a threadsafe pool of network connections.

And, since we don't want multiple instances of Redis clients floating around at any given time during the life cycle of our application, we should create our RedisClient class on the principle of the singleton design pattern.

First, let's create a private constructor for our client that'll internally initialize the JedisPool when an instance of RedisClient class is created:

private static JedisPool jedisPool; private RedisClient(String ip, int port) { try { if (jedisPool == null) { jedisPool = new JedisPool(new URI("//" + ip + ":" + port)); } } catch (URISyntaxException e) { log.error("Malformed server address", e); } }

Next, we need a point of access to our singleton client. So, let's create a static method getInstance() for this purpose:

private static volatile RedisClient instance = null; public static RedisClient getInstance(String ip, final int port) { if (instance == null) { synchronized (RedisClient.class) { if (instance == null) { instance = new RedisClient(ip, port); } } } return instance; }

Finally, let's see how we can create a wrapper method on top of Jedis's lrange method:

public List lrange(final String key, final long start, final long stop) { try (Jedis jedis = jedisPool.getResource()) { return jedis.lrange(key, start, stop); } catch (Exception ex) { log.error("Exception caught in lrange", ex); } return new LinkedList(); }

Of course, we can follow the same strategy to create the rest of the wrapper methods such as lpush, hmset, hgetall, sadd, smembers, keys, zadd, and zrange.

4.3. Analysis

All the Redis commands that we can use to explore a collection in a single go will naturally have an O(n) time complexity in the best case.

We are perhaps a bit liberal, calling this approach as naive. In a real-life production instance of Redis, it's quite common to have thousands or millions of keys in a single collection. Further, Redis's single-threaded nature brings more misery, and our approach could catastrophically block other higher-priority operations.

So, we should make it a point that we're limiting our naive approach to be used only for debugging purposes.

5. Iterator Basics

The major flaw in our naive implementation is that we're requesting Redis to give us all of the results for our single fetch-query in one go. To overcome this issue, we can break our original fetch query into multiple sequential fetch queries that operate on smaller chunks of the entire dataset.

Let's assume that we have a 1,000-page book that we're supposed to read. If we follow our naive approach, we'll have to read this large book in a single sitting without any breaks. That'll be fatal to our well-being as it'll drain our energy and prevent us from doing any other higher-priority activity.

Of course, the right way is to finish the book over multiple reading sessions. In each session, we resume from where we left off in the previous session — we can track our progress by using a page bookmark.

Although the total reading time in both cases will be of comparable value, nonetheless, the second approach is better as it gives us room to breathe.

Let's see how we can use an iterator-based approach for exploring Redis collections.

6. Redis Scan

Redis offers several scanning strategies to read keys from collections using a cursor-based approach, which is, in principle, similar to a page bookmark.

6.1. Scan Strategies

We can scan through the entire key-value collection store using the Scan command. However, if we want to limit our dataset by collection types, then we can use one of the variants:

  • Sscan can be used for iterating through sets
  • Hscan helps us iterate through pairs of field-value in a hash
  • Zscan allows an iteration through members stored in a sorted set

We must note that we don't really need a server-side scan strategy specifically designed for the linked lists. That's because we can access members of the linked list through indexes using the lindex or lrange command. Plus, we can find out the number of elements and use lrange in a simple loop to iterate the entire list in small chunks.

Let's use the SCAN command to scan over keys of string type. To start the scan, we need to use the cursor value as “0”, matching pattern string as “ball*”:

127.0.0.1:6379> mset balls:cricket 160 balls:football 450 balls:volleyball 270 OK 127.0.0.1:6379> SCAN 0 MATCH ball* COUNT 1 1) "2" 2) 1) "balls:cricket" 127.0.0.1:6379> SCAN 2 MATCH ball* COUNT 1 1) "3" 2) 1) "balls:volleyball" 127.0.0.1:6379> SCAN 3 MATCH ball* COUNT 1 1) "0" 2) 1) "balls:football"

With each completed scan, we get the next value of cursor to be used in the subsequent iteration. Eventually, we know that we've scanned through the entire collection when the next cursor value is “0”.

7. Scanning With Java

By now, we have enough understanding of our approach that we can start implementing it in Java.

7.1. Scanning Strategies

If we peek into the core scanning functionality offered by the Jedis class, we'll find strategies to scan different collection types:

public ScanResult scan(final String cursor, final ScanParams params); public ScanResult sscan(final String key, final String cursor, final ScanParams params); public ScanResult
     
       hscan(final String key, final String cursor, final ScanParams params); public ScanResult zscan(final String key, final String cursor, final ScanParams params);
     

Jedis requires two optional parameters, search-pattern and result-size, to effectively control the scanning – ScanParams makes this happen. For this purpose, it relies on the match() and count() methods, which are loosely based on the builder design pattern:

public ScanParams match(final String pattern); public ScanParams count(final Integer count);

Now that we've soaked in the basic knowledge about Jedis's scanning approach, let's model these strategies through a ScanStrategy interface:

public interface ScanStrategy { ScanResult scan(Jedis jedis, String cursor, ScanParams scanParams); }

First, let's work on the simplest scan strategy, which is independent of the collection-type and reads the keys, but not the value of the keys:

public class Scan implements ScanStrategy { public ScanResult scan(Jedis jedis, String cursor, ScanParams scanParams) { return jedis.scan(cursor, scanParams); } }

Next, let's pick up the hscan strategy, which is tailored to read all the field keys and field values of a particular hash key:

public class Hscan implements ScanStrategy
     
       { private String key; @Override public ScanResult
      
        scan(Jedis jedis, String cursor, ScanParams scanParams) { return jedis.hscan(key, cursor, scanParams); } }
      
     

Finally, let's build the strategies for sets and sorted sets. The sscan strategy can read all the members of a set, whereas the zscan strategy can read the members along with their scores in the form of Tuples:

public class Sscan implements ScanStrategy { private String key; public ScanResult scan(Jedis jedis, String cursor, ScanParams scanParams) { return jedis.sscan(key, cursor, scanParams); } } public class Zscan implements ScanStrategy { private String key; @Override public ScanResult scan(Jedis jedis, String cursor, ScanParams scanParams) { return jedis.zscan(key, cursor, scanParams); } }

7.2. Redis Iterator

Next, let's sketch out the building blocks needed to build our RedisIterator class:

  • String-based cursor
  • Scanning strategy such as scan, sscan, hscan, zscan
  • Placeholder for scanning parameters
  • Access to JedisPool to get a Jedis resource

We can now go ahead and define these members in our RedisIterator class:

private final JedisPool jedisPool; private ScanParams scanParams; private String cursor; private ScanStrategy strategy;

Our stage is all set to define the iterator-specific functionality for our iterator. For that, our RedisIterator class must implement the Iterator interface:

public class RedisIterator implements Iterator
     
       { }
     

Naturally, we are required to override the hasNext() and next() methods inherited from the Iterator interface.

First, let's pick the low-hanging fruit – the hasNext() method – as the underlying logic is straight-forward. As soon as the cursor value becomes “0”, we know that we're done with the scan. So, let's see how we can implement this in just one-line:

@Override public boolean hasNext() { return !"0".equals(cursor); }

Next, let's work on the next() method that does the heavy lifting of scanning:

@Override public List next() { if (cursor == null) { cursor = "0"; } try (Jedis jedis = jedisPool.getResource()) { ScanResult scanResult = strategy.scan(jedis, cursor, scanParams); cursor = scanResult.getCursor(); return scanResult.getResult(); } catch (Exception ex) { log.error("Exception caught in next()", ex); } return new LinkedList(); }

We must note that ScanResult not only gives the scanned results but also the next cursor-value needed for the subsequent scan.

Finally, we can enable the functionality to create our RedisIterator in the RedisClient class:

public RedisIterator iterator(int initialScanCount, String pattern, ScanStrategy strategy) { return new RedisIterator(jedisPool, initialScanCount, pattern, strategy); }

7.3. Read With Redis Iterator

As we've designed our Redis iterator with the help of the Iterator interface, it's quite intuitive to read the collection values with the help of the next() method as long as hasNext() returns true.

For the sake of completeness and simplicity, we'll first store the dataset related to the sports-balls in a Redis hash. After that, we'll use our RedisClient to create an iterator using Hscan scanning strategy. Let's test our implementation by seeing this in action:

@Test public void testHscanStrategy() { HashMap hash = new HashMap(); hash.put("cricket", "160"); hash.put("football", "450"); hash.put("volleyball", "270"); redisClient.hmset("balls", hash); Hscan scanStrategy = new Hscan("balls"); int iterationCount = 2; RedisIterator iterator = redisClient.iterator(iterationCount, "*", scanStrategy); List
     
       results = new LinkedList
      
       (); while (iterator.hasNext()) { results.addAll(iterator.next()); } Assert.assertEquals(hash.size(), results.size()); }
      
     

We can follow the same thought process with little modification to test and implement the remaining strategies to scan and read the keys available in different types of collections.

8. Conclusion

Kami memulai tutorial ini dengan maksud untuk mempelajari tentang bagaimana kami dapat membaca semua kunci yang cocok di Redis.

Kami menemukan bahwa ada cara sederhana yang ditawarkan oleh Redis untuk membaca kunci sekaligus. Meskipun sederhana, kami membahas bagaimana hal ini membebani sumber daya dan oleh karena itu tidak cocok untuk sistem produksi. Saat menggali lebih dalam, kami mengetahui bahwa ada pendekatan berbasis iterator untuk memindai melalui kunci Redis yang cocok untuk kueri baca kami.

Seperti biasa, kode sumber lengkap untuk implementasi Java yang digunakan dalam artikel ini tersedia di GitHub.

Jawa bawah

Saya baru saja mengumumkan kursus Learn Spring baru , yang berfokus pada dasar-dasar Spring 5 dan Spring Boot 2:

>> LIHAT KURSUSnya