Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs(memorystore): added valkey leaderboard snippets #10003

Draft
wants to merge 10 commits into
base: main
Choose a base branch
from
Empty file.
117 changes: 117 additions & 0 deletions memorystore/valkey/leaderboard/snippets/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
<?xml version="1.0" encoding="UTF-8"?>

<!--
Copyright 2020 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.
-->

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.example.memorystore</groupId>
<artifactId>caching</artifactId>
<version>1.0-SNAPSHOT</version>

<name>Google Cloud Memorystore Sample</name>
<url>http://www.example.com</url>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.release>11</maven.compiler.release>
</properties>

<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.junit</groupId>
<artifactId>junit-bom</artifactId>
<version>5.11.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>

<dependencies>
<!-- Jedis Redis client library -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>4.3.1</version>
</dependency>

<!-- Google Cloud Client Libraries -->
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>google-cloud-core</artifactId>
<version>2.16.0</version>
</dependency>

<!-- Unit testing libraries -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-params</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<pluginManagement>
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.4.0</version>
</plugin>
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.3.1</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.13.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.3.0</version>
</plugin>
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<version>3.4.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>3.1.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>3.1.2</version>
</plugin>
<plugin>
<artifactId>maven-site-plugin</artifactId>
<version>3.12.1</version>
</plugin>
<plugin>
<artifactId>maven-project-info-reports-plugin</artifactId>
<version>3.6.1</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
Original file line number Diff line number Diff line change
@@ -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 redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.AbstractMap.SimpleEntry;
import java.util.List;

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<SimpleEntry<String, Double>> 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<String, Double> 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 (String userKey : USER_SCORES.keySet()) {
// 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());
}
}
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should we rename the 'filter' file names to 'sortby' as well?

Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
/*
* 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 redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.AbstractMap.SimpleEntry;
import java.util.List;
import java.util.Set;

public final class MemorystoreFilterByAsc {

/** 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<SimpleEntry<String, Double>> 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 MemorystoreFilterByAsc() {
// 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<String, Double> 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
Set<String> sortedUsers = jedis.zrange(LEADERBOARD_KEY, 0, -1);

// Print the leaderboard in ascending order
System.out.printf("Leaderboad (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());
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
/*
* 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 redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.AbstractMap.SimpleEntry;
import java.util.List;
import java.util.Set;

public final class MemorystoreFilterByDesc {

/** 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<SimpleEntry<String, Double>> 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 MemorystoreFilterByDesc() {
// 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<String, Double> entry : USER_SCORES) {
jedis.zadd(LEADERBOARD_KEY, entry.getKey(), user.value());
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):");
Set<String> 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:");
Set<String> 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());
}
}
}
Loading