Skip to content

Commit

Permalink
docs(memorystore): added valkey session practical sourcecode samples
Browse files Browse the repository at this point in the history
  • Loading branch information
dackers86 committed Jan 29, 2025
1 parent 4f6d504 commit fdeeb82
Show file tree
Hide file tree
Showing 7 changed files with 441 additions and 0 deletions.
Empty file.
117 changes: 117 additions & 0 deletions memorystore/valkey/session/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,65 @@
/*
* 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 IMPLIED WARRANTIES 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;

public final class MemorystoreAddItemToBasket {

/** 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;

/** User ID for managing the basket */
private static final String USER_ID = "USERID";

/** Item to be added to the user's basket */
private static final String ITEM_ID = "ITEM_ID";

private MemorystoreAddItemToBasket() {
// No-op; won't be called
}

/**
* Adds an item to a user's basket in Memorystore.
*
* @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()) {
String basketKey = "basket:" + USER_ID;

// Add a single item to the user's basket
jedis.sadd(basketKey, ITEM);
System.out.printf("Added item to basket: %s%n", ITEM_ID);

// Verify the item is in the basket
boolean exists = jedis.sismember(basketKey, ITEM);
if (exists) {
System.out.printf("Item successfully added: %s%n", ITEM_ID);
} else {
System.out.printf("Failed to add item: %s%n", ITEM_ID);
}
} 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,60 @@
/*
* 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 IMPLIED WARRANTIES 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;

public final class MemorystoreClearBasket {

/** 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;

/** User ID for managing the basket */
private static final String USER_ID = "USERID";

private MemorystoreClearBasket() {
// No-op; won't be called
}

/**
* Clears a user's basket in Memorystore.
*
* @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()) {
String basketKey = "basket:" + USER_ID;

// Delete the basket (remove all items)
long deleted = jedis.del(basketKey);

// Verify if the basket was cleared
if (deleted > 0) {
System.out.printf("Basket cleared successfully for user: %s%n", USER_ID);
} else {
System.out.printf("No basket found for user: %s%n", USER_ID);
}
} 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,68 @@
/*
* 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;

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;

/** Replace the id of the item to write to Memorystore. */
private static final String TOKEN = "TOKEN";

private MemorystoreFilterByDesc() {
// No-op; won't be called
}

/**
* Writes to Memorystore with a Time-to-live(TTL) value.
*
* @param args command-line arguments
* @throws InterruptedException if the thread sleep is interrupted
*/
public static void main(final String[] args) throws InterruptedException {
// Connect to the Memorystore instance
JedisPool pool = new JedisPool(INSTANCE_ID, PORT);

try (Jedis jedis = pool.getResource()) {
// Set a TTL of 10 seconds during entry creation
final int ttlSeconds = 10;
jedis.del(TOKEN);

// Verify the user has been deleted
System.out.println("Verifying cache.");
String cachedUser = jedis.exist(TOKEN);

// Print the cached item if found
if (cachedUser != null) {
System.out.printf("Found cached item: %s%n", cachedUser);
}

// Print the cached item not found
if (cachedUser == null) {
System.out.printf("No cached item found: %s%n", ITEM_ID);
}
} catch (Exception e) {
// Print any errors found in the exception
System.err.printf("Error connecting to Redis: %s%n", e.getMessage());
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
/*
* 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 IMPLIED WARRANTIES 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.UUID;

public final class MemorystoreLoginUser {

/** 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;

/** User ID for login */
private static final String USER_ID = "USERID";

/** Session expiration time in seconds (30 minutes) */
private static final int SESSION_TIMEOUT = 1800;

private MemorystoreLoginUser() {
// No-op; won't be called
}

/**
* Logs in a user by creating a session in Memorystore.
*
* @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()) {
String sessionKey = "session:" + USER_ID;

// Check if the user is already logged in
if (jedis.exists(sessionKey)) {
System.out.printf("User %s is already logged in.%n", USER_ID);
return;
}

// Generate a session token
String sessionToken = UUID.randomUUID().toString();

// Store the session token in Redis with an expiration time
jedis.setex(sessionKey, SESSION_TIMEOUT, sessionToken);
System.out.printf("User %s logged in with session: %s%n", USER_ID, sessionToken);
} catch (Exception e) {
System.err.printf("Error connecting to Redis: %s%n", e.getMessage());
}
}
}
Loading

0 comments on commit fdeeb82

Please sign in to comment.