Add in-memory cache to KeyValueStore

This commit is contained in:
AsamK 2025-02-27 16:41:59 +01:00
parent d3d2caac5a
commit 141d3326ab

View file

@ -10,6 +10,7 @@ import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.sql.Types; import java.sql.Types;
import java.util.HashMap;
import java.util.Objects; import java.util.Objects;
public class KeyValueStore { public class KeyValueStore {
@ -18,6 +19,7 @@ public class KeyValueStore {
private static final Logger logger = LoggerFactory.getLogger(KeyValueStore.class); private static final Logger logger = LoggerFactory.getLogger(KeyValueStore.class);
private final Database database; private final Database database;
private final HashMap<KeyValueEntry<?>, Object> cache = new HashMap<>();
public static void createSql(Connection connection) throws SQLException { public static void createSql(Connection connection) throws SQLException {
// When modifying the CREATE statement here, also add a migration in AccountDatabase.java // When modifying the CREATE statement here, also add a migration in AccountDatabase.java
@ -36,7 +38,14 @@ public class KeyValueStore {
this.database = database; this.database = database;
} }
@SuppressWarnings("unchecked")
public <T> T getEntry(KeyValueEntry<T> key) { public <T> T getEntry(KeyValueEntry<T> key) {
synchronized (cache) {
if (cache.containsKey(key)) {
logger.trace("Got entry for key {} from cache", key.key());
return (T) cache.get(key);
}
}
try (final var connection = database.getConnection()) { try (final var connection = database.getConnection()) {
return getEntry(connection, key); return getEntry(connection, key);
} catch (SQLException e) { } catch (SQLException e) {
@ -63,11 +72,17 @@ public class KeyValueStore {
try (final var statement = connection.prepareStatement(sql)) { try (final var statement = connection.prepareStatement(sql)) {
statement.setString(1, key.key()); statement.setString(1, key.key());
final var result = Utils.executeQueryForOptional(statement, var result = Utils.executeQueryForOptional(statement, resultSet -> readValueFromResultSet(key, resultSet))
resultSet -> readValueFromResultSet(key, resultSet)).orElse(null); .orElse(null);
if (result == null) { if (result == null) {
return key.defaultValue(); logger.trace("Got entry for key {} from default value", key.key());
result = key.defaultValue();
} else {
logger.trace("Got entry for key {} from db", key.key());
}
synchronized (cache) {
cache.put(key, result);
} }
return result; return result;
} }
@ -95,6 +110,9 @@ public class KeyValueStore {
setParameterValue(statement, 2, key.clazz(), value); setParameterValue(statement, 2, key.clazz(), value);
statement.executeUpdate(); statement.executeUpdate();
} }
synchronized (cache) {
cache.put(key, value);
}
return true; return true;
} }