Skip to main content

Execute Commands

Hint

This article is generated by AI translation.

Use JdbcTemplate to run Redis commands directly for read/write operations. Make sure the Redis data source is configured properly; see the Redis driver guide.

Tip

For more usage details see the JdbcTemplate class. The following features are unavailable due to driver limitations:

  • Batch operations
  • Stored procedures

JdbcTemplate interface

Instantiate JdbcTemplate with an existing DataSource or Connection.

Create JdbcTemplate
JdbcTemplate jdbc = new JdbcTemplate(dataSource);
// or
JdbcTemplate jdbc = new JdbcTemplate(connection);

Key read/write/delete

Read a key
// Raw command
String result1 = jdbc.queryForString("GET myKey");
// Command with bind arguments
String result2 = jdbc.queryForString("GET ?", "myKey");
Write a key
// Raw command
int result1 = jdbc.executeUpdate("SET myKey myValue");
// Command with bind arguments
int result2 = jdbc.executeUpdate("SET ? ?", new Object[] { "myKey", "myValue" });
Delete a key
// Raw command
int result1 = jdbc.executeUpdate("DEL myKey");
// Command with bind arguments
int result2 = jdbc.executeUpdate("DEL ?", "myKey");

Key read/write/delete (multiple keys)

Read multiple keys
// Raw command
Map<String, Integer> result1= jdbc.queryForPairs("MGET key1 key2 key3", String.class, Integer.class);
// Command with bind arguments
Map<String, Integer> result2 = jdbc.queryForPairs("MGET ? ? ?", String.class, Integer.class, new Object[] { "key1", "key2", "key3" });
Write multiple keys
// Raw command
int result1 = jdbc.executeUpdate("MSET key1 123 key2 456 key3 789");
// Command with bind arguments
int result2 = jdbc.executeUpdate("MSET ? ? ? ? ? ?", new Object[] { "key1", "value1", "key2", "value2", "key3", "value3" });
Delete multiple keys
// Raw command
int result1 = jdbc.executeUpdate("DEL key1 key2 key3");
// Command with bind arguments
int result2 = jdbc.executeUpdate("DEL ? ? ?", new Object[] { "key1", "key2", "key3" });

Read/write/delete objects

Bind JSON serialization with @BindTypeHandler
@BindTypeHandler(JsonTypeHandler.class)
public class MyObject {
...
}
Read an object
// Raw command
MyObject result1 = jdbc.queryForObject("GET myObjectKey", MyObject.class);
// Command with bind arguments
MyObject result2 = jdbc.queryForObject("GET ?", MyObject.class, "myObjectKey");
Write an object
// Command with bind arguments
int result1 = jdbc.executeUpdate("SET ? ?", new Object[] { "myObjectKey", (MyObject) myObject });
Delete an object
// Raw command
int result1 = jdbc.executeUpdate("DEL myObjectKey");
// Command with bind arguments
int result2 = jdbc.executeUpdate("DEL ?", "myObjectKey");

Supported Commands

See the full supported command list for Redis coverage.