diff --git a/memorystore/valkey/leaderboard/snippets/README.md b/memorystore/valkey/leaderboard/snippets/README.md new file mode 100644 index 00000000000..e69de29bb2d diff --git a/memorystore/valkey/leaderboard/snippets/pom.xml b/memorystore/valkey/leaderboard/snippets/pom.xml new file mode 100644 index 00000000000..9ac9e5dfbb4 --- /dev/null +++ b/memorystore/valkey/leaderboard/snippets/pom.xml @@ -0,0 +1,127 @@ + + + + + + 4.0.0 + + com.example.memorystore + caching + 1.0-SNAPSHOT + + Google Cloud Memorystore Sample + http://www.example.com + + + + com.google.cloud.samples + shared-configuration + 1.2.0 + + + + UTF-8 + 11 + + + + + + org.junit + junit-bom + 5.11.0 + pom + import + + + + + + + + redis.clients + jedis + 4.3.1 + + + + + com.google.cloud + google-cloud-core + 2.16.0 + + + + + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-params + test + + + + + + + + maven-clean-plugin + 3.4.0 + + + maven-resources-plugin + 3.3.1 + + + maven-compiler-plugin + 3.13.0 + + + maven-surefire-plugin + 3.3.0 + + + maven-jar-plugin + 3.4.2 + + + maven-install-plugin + 3.1.2 + + + maven-deploy-plugin + 3.1.2 + + + maven-site-plugin + 3.12.1 + + + maven-project-info-reports-plugin + 3.6.1 + + + + + \ No newline at end of file diff --git a/memorystore/valkey/leaderboard/snippets/src/main/java/samples/MemorystoreAddScore.java b/memorystore/valkey/leaderboard/snippets/src/main/java/samples/MemorystoreAddScore.java new file mode 100644 index 00000000000..d3ec5a20c4e --- /dev/null +++ b/memorystore/valkey/leaderboard/snippets/src/main/java/samples/MemorystoreAddScore.java @@ -0,0 +1,76 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.util.AbstractMap.SimpleEntry; +import java.util.List; +import redis.clients.jedis.Jedis; +import redis.clients.jedis.JedisPool; + +public final class MemorystoreAddScore { + + /** Replace the Memorystore instance id. */ + private static final String INSTANCE_ID = "INSTANCE_ID"; + + /** Replace the Memorystore port, if not the default port. */ + private static final int PORT = 6379; + + /** Set the name for the Leaderboard */ + private static final String LEADERBOARD_KEY = "leaderboard"; + + /** Replace the names and scores to write to Memorystore. */ + private static final List> USER_SCORES = List.of( + new SimpleEntry<>("User1", 100.0), + new SimpleEntry<>("User2", 80.0), + new SimpleEntry<>("User3", 95.0), + new SimpleEntry<>("User4", 70.0)); + + private MemorystoreAddScore() { + // No-op; won't be called + } + + /** + * Writes to Memorystore before verifying the item exists. + * + * @param args command-line arguments + */ + public static void main(final String[] args) { + // Connect to the Memorystore instance + JedisPool pool = new JedisPool(INSTANCE_ID, PORT); + + try (Jedis jedis = pool.getResource()) { + // Add the scores to the leaderboard + for (SimpleEntry entry : USER_SCORES) { + jedis.zadd(LEADERBOARD_KEY, entry.getValue(), entry.getKey()); + System.out.printf( + "Added/Updated %s with score %s%n", entry.getKey(), entry.getValue()); + } + + // Verify that scores have been added + for (SimpleEntry entry : USER_SCORES) { + String userKey = entry.getKey(); + + // Find the user score based on the user key + Double userScore = jedis.zscore(LEADERBOARD_KEY, userKey); + + // Print out the user score + System.out.printf("User %s has a score of %s%n", userKey, userScore); + } + } catch (Exception e) { + // Print any errors found in the exception + System.err.printf("Error connecting to Redis: %s%n", e.getMessage()); + } + } +} diff --git a/memorystore/valkey/leaderboard/snippets/src/main/java/samples/MemorystoreLeaderboardPagination.java b/memorystore/valkey/leaderboard/snippets/src/main/java/samples/MemorystoreLeaderboardPagination.java new file mode 100644 index 00000000000..719a7fb780d --- /dev/null +++ b/memorystore/valkey/leaderboard/snippets/src/main/java/samples/MemorystoreLeaderboardPagination.java @@ -0,0 +1,112 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.util.AbstractMap.SimpleEntry; +import java.util.List; +import redis.clients.jedis.Jedis; +import redis.clients.jedis.JedisPool; + +public final class MemorystoreLeaderboardPagination { + + /** Replace the Memorystore instance id. */ + private static final String INSTANCE_ID = "INSTANCE_ID"; + + /** Replace the Memorystore port, if not the default port. */ + private static final int PORT = 6379; + + /** Set the name for the Leaderboard */ + private static final String LEADERBOARD_KEY = "leaderboard"; + + /** Number of users per page */ + private static final int PAGE_SIZE = 2; + + /** Sample user scores */ + private static final List> USER_SCORES = List.of( + new SimpleEntry<>("User1", 100.0), + new SimpleEntry<>("User2", 80.0), + new SimpleEntry<>("User3", 95.0), + new SimpleEntry<>("User4", 70.0), + new SimpleEntry<>("User5", 60.0), + new SimpleEntry<>("User6", 50.0)); + + private MemorystoreLeaderboardPagination() { + // No-op; won't be called + } + + /** + * Writes to Memorystore and retrieves the leaderboard using pagination. + * + * @param args command-line arguments (page number) + */ + public static void main(final String[] args) { + // Validate input arguments + int pageNumber = args.length > 0 ? Integer.parseInt(args[0]) : 1; + if (pageNumber < 1) { + System.out.println("Invalid page number. Defaulting to page 1."); + pageNumber = 1; + } + + // Connect to the Memorystore instance + JedisPool pool = new JedisPool(INSTANCE_ID, PORT); + + try (Jedis jedis = pool.getResource()) { + // Add the scores to the leaderboard + for (SimpleEntry entry : USER_SCORES) { + jedis.zadd(LEADERBOARD_KEY, entry.getValue(), entry.getKey()); + System.out.printf( + "Added/Updated %s with score %s%n", entry.getKey(), entry.getValue()); + } + + // Display Users on page 1 + System.out.printf("\nLeaderboard - Page %d:\n", 1); + displayPaginatedLeaderboard(jedis, 1); + + // Display Users on page 2 + System.out.printf("\nLeaderboard - Page %d:\n", 2); + displayPaginatedLeaderboard(jedis, 2); + } catch (Exception e) { + System.err.printf("Error connecting to Redis: %s%n", e.getMessage()); + } + } + + /** + * Fetches and displays leaderboard users based on the given page number. + * + * @param jedis Redis client instance + * @param page The page number to fetch + */ + private static void displayPaginatedLeaderboard(Jedis jedis, int page) { + // Caulcate the start and end index for each page + int start = (page - 1) * PAGE_SIZE; + int end = start + PAGE_SIZE - 1; + + // Use zrevrange to find users between the start and end index + List paginatedUsers = jedis.zrevrange(LEADERBOARD_KEY, start, end); + + // If no users are found, print a message and return + if (paginatedUsers.isEmpty()) { + System.out.println("No users found on this page."); + return; + } + + int ranking = start + 1; + for (String user : paginatedUsers) { + System.out.printf( + "Rank %d: %s, Score: %s%n", + ranking++, user, jedis.zscore(LEADERBOARD_KEY, user)); + } + } +} diff --git a/memorystore/valkey/leaderboard/snippets/src/main/java/samples/MemorystoreSortByScoreAsc.java b/memorystore/valkey/leaderboard/snippets/src/main/java/samples/MemorystoreSortByScoreAsc.java new file mode 100644 index 00000000000..060a02d1562 --- /dev/null +++ b/memorystore/valkey/leaderboard/snippets/src/main/java/samples/MemorystoreSortByScoreAsc.java @@ -0,0 +1,77 @@ +/* +* Copyright 2025 Google LLC +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +import java.util.AbstractMap.SimpleEntry; +import java.util.List; +import redis.clients.jedis.Jedis; +import redis.clients.jedis.JedisPool; + +public final class MemorystoreSortByScoreAsc { + + /** Replace the Memorystore instance id. */ + private static final String INSTANCE_ID = "INSTANCE_ID"; + + /** Replace the Memorystore port, if not the default port. */ + private static final int PORT = 6379; + + /** Set the name for the Leaderboard */ + private static final String LEADERBOARD_KEY = "leaderboard"; + + /** Replace the names and scores to write to Memorystore. */ + private static final List> USER_SCORES = List.of( + new SimpleEntry<>("User1", 100.0), + new SimpleEntry<>("User2", 80.0), + new SimpleEntry<>("User3", 95.0), + new SimpleEntry<>("User4", 70.0)); + + private MemorystoreSortByScoreAsc() { + // No-op; won't be called + } + + /** + * Writes to Memorystore and retrieves the leaderboard sorted in ascending + * order. + * + * @param args command-line arguments + */ + public static void main(final String[] args) { + // Connect to the Memorystore instance + JedisPool pool = new JedisPool(INSTANCE_ID, PORT); + + try (Jedis jedis = pool.getResource()) { + // Add the scores to the leaderboard + for (SimpleEntry entry : USER_SCORES) { + jedis.zadd(LEADERBOARD_KEY, entry.getValue(), entry.getKey()); + System.out.printf( + "Added/Updated %s with score %s%n", entry.getKey(), entry.getValue()); + } + + // Retrieve and print all users sorted by score in ascending order + List sortedUsers = jedis.zrange(LEADERBOARD_KEY, 0, -1); + + // Print the leaderboard in ascending order + System.out.println("\nLeaderboad (Ascending)"); + + // For each user, print the score + for (String user : sortedUsers) { + System.out.printf( + "User: %s, Score: %s%n", user, jedis.zscore(LEADERBOARD_KEY, user)); + } + } catch (Exception e) { + System.err.printf("Error connecting to Redis: %s%n", e.getMessage()); + } + } +} diff --git a/memorystore/valkey/leaderboard/snippets/src/main/java/samples/MemorystoreSortByScoreDesc.java b/memorystore/valkey/leaderboard/snippets/src/main/java/samples/MemorystoreSortByScoreDesc.java new file mode 100644 index 00000000000..56e8db22a43 --- /dev/null +++ b/memorystore/valkey/leaderboard/snippets/src/main/java/samples/MemorystoreSortByScoreDesc.java @@ -0,0 +1,88 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.util.AbstractMap.SimpleEntry; +import java.util.List; +import redis.clients.jedis.Jedis; +import redis.clients.jedis.JedisPool; + +public final class MemorystoreSortByScoreDesc { + + /** Replace the Memorystore instance id. */ + private static final String INSTANCE_ID = "INSTANCE_ID"; + + /** Replace the Memorystore port, if not the default port. */ + private static final int PORT = 6379; + + /** Set the name for the Leaderboard */ + private static final String LEADERBOARD_KEY = "leaderboard"; + + /** Replace the names and scores to write to Memorystore. */ + private static final List> USER_SCORES = List.of( + new SimpleEntry<>("User1", 100.0), + new SimpleEntry<>("User2", 80.0), + new SimpleEntry<>("User3", 95.0), + new SimpleEntry<>("User4", 70.0)); + + private MemorystoreSortByScoreDesc() { + // No-op; won't be called + } + + /** + * Writes to Memorystore and retrieves the leaderboard sorted in descending + * order. + * + * @param args command-line arguments + */ + public static void main(final String[] args) { + // Connect to the Memorystore instance + JedisPool pool = new JedisPool(INSTANCE_ID, PORT); + + try (Jedis jedis = pool.getResource()) { + // Add the scores to the leaderboard + for (SimpleEntry entry : USER_SCORES) { + String user = entry.getKey(); + double score = entry.getValue(); + + jedis.zadd(LEADERBOARD_KEY, score, user); + System.out.printf("Added/Updated %s with score %s%n", user, score); + } + + // Retrieve and print all users sorted by score in descending order + System.out.println("\nLeaderboard (Sorted by Descending Scores):"); + List sortedUsers = jedis.zrevrange(LEADERBOARD_KEY, 0, -1); + + // Print the leaderboard in descending order + for (String user : sortedUsers) { + System.out.printf( + "User: %s, Score: %s%n", user, jedis.zscore(LEADERBOARD_KEY, user)); + } + + // Get the highest-ranked user + System.out.println("\nTop Ranked User:"); + List topUser = jedis.zrevrange(LEADERBOARD_KEY, 0, 0); + if (!topUser.isEmpty()) { + String user = topUser.iterator().next(); + System.out.printf( + "User: %s, Score: %s%n", user, jedis.zscore(LEADERBOARD_KEY, user)); + } else { + System.out.println("Leaderboard is empty."); + } + } catch (Exception e) { + System.err.printf("Error connecting to Redis: %s%n", e.getMessage()); + } + } +}