Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,6 @@ private DatabaseConfig buildDatabaseConfig() {
// Caching
DatabaseConfig.CachingConfig cachingConfig = dbConfig.getCaching();
cachingConfig.setDefaultTTL(config.getLong("caching.defaultTTL", 3600));
cachingConfig.setPlayerDataTTL(config.getLong("caching.playerDataTTL", 7200));
cachingConfig.setAutoRefresh(config.getBoolean("caching.autoRefresh", true));
cachingConfig.setRefreshThreshold(config.getLong("caching.refreshThreshold", 300));

Expand Down
3 changes: 1 addition & 2 deletions yrdatabase-allay/src/main/resources/config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,7 @@ persist:

# Caching behavior
caching:
defaultTTL: 3600
playerDataTTL: 7200
defaultTTL: 3600 # seconds
autoRefresh: true
refreshThreshold: 300

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,16 @@ public interface DatabaseManager extends AutoCloseable {
*/
CompletableFuture<Optional<Map<String, Object>>> get(String table, String key);

/**
* Smart get: tries cache first, then persistence layer.
*
* @param table Table name
* @param key Primary key
* @param TTLSeconds Custom TTL time(Seconds)
* @return Data map wrapped in Optional
*/
CompletableFuture<Optional<Map<String, Object>>> get(String table, String key, int TTLSeconds);

/**
* Smart set: writes to cache with optional delayed persistence.
*
Expand All @@ -47,6 +57,17 @@ public interface DatabaseManager extends AutoCloseable {
*/
CompletableFuture<Boolean> set(String table, String key, Map<String, Object> data, CacheStrategy strategy);

/**
* Smart set with cache strategy.
*
* @param table Table name
* @param key Primary key
* @param data Data to store
* @param strategy Cache strategy
* @param TTLSeconds Custom TTL time(Seconds)
* @return Success status
*/
CompletableFuture<Boolean> set(String table, String key, Map<String, Object> data, CacheStrategy strategy, int TTLSeconds);
/**
* Persist data from cache to persistence layer and clear cache.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,6 @@ public static class SQLiteConfig {
@Data
public static class CachingConfig {
private long defaultTTL = 3600;
private long playerDataTTL = 7200;
private boolean autoRefresh = true;
private long refreshThreshold = 300;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,6 @@ void shouldHaveDefaultTtlValues() {
DatabaseConfig config = new DatabaseConfig();

assertEquals(3600, config.getCaching().getDefaultTTL());
assertEquals(7200, config.getCaching().getPlayerDataTTL());
}

@Test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,11 @@ public CompletableFuture<Void> flush() {

@Override
public CompletableFuture<Optional<Map<String, Object>>> get(String table, String key) {
return get(table,key,0);
}

@Override
public CompletableFuture<Optional<Map<String, Object>>> get(String table, String key, int TTLSeconds) {
String cacheKey = buildCacheKey(table, key);

// Try cache first
Expand All @@ -135,6 +140,7 @@ public CompletableFuture<Optional<Map<String, Object>>> get(String table, String
// Write back to cache
String json = gson.toJson(persisted.get());
long ttl = config.getCaching().getDefaultTTL();
if(TTLSeconds > 0)ttl = TTLSeconds;
redisProvider.setEx(cacheKey, json, Duration.ofSeconds(ttl));
}
return CompletableFuture.completedFuture(persisted);
Expand Down Expand Up @@ -167,10 +173,16 @@ public CompletableFuture<Boolean> set(String table, String key, Map<String, Obje

@Override
public CompletableFuture<Boolean> set(String table, String key, Map<String, Object> data, CacheStrategy strategy) {
return set(table, key, data, strategy,0);
}

@Override
public CompletableFuture<Boolean> set(String table, String key, Map<String, Object> data, CacheStrategy strategy, int TTLSeconds) {
String cacheKey = buildCacheKey(table, key);
String json = gson.toJson(data);
long ttl = config.getCaching().getDefaultTTL();

if(TTLSeconds > 0)ttl = TTLSeconds;
final long finalTTL = ttl;
// Ensure data has the key
Map<String, Object> dataWithKey = new HashMap<>(data);
dataWithKey.put("id", key);
Expand All @@ -189,7 +201,7 @@ public CompletableFuture<Boolean> set(String table, String key, Map<String, Obje
CompletableFuture<Boolean> persistFuture = saveToPersist(table, key, dataWithKey);
if (redisProvider != null && redisProvider.isConnected()) {
return persistFuture.thenCompose(persistOk ->
redisProvider.setEx(cacheKey, json, Duration.ofSeconds(ttl))
redisProvider.setEx(cacheKey, json, Duration.ofSeconds(finalTTL))
.thenApply(cacheOk -> persistOk && cacheOk)
);
}
Expand All @@ -199,12 +211,12 @@ public CompletableFuture<Boolean> set(String table, String key, Map<String, Obje
default:
if (redisProvider != null && redisProvider.isConnected()) {
// 先保存到缓存
return redisProvider.setEx(cacheKey, json, Duration.ofSeconds(ttl))
return redisProvider.setEx(cacheKey, json, Duration.ofSeconds(finalTTL))
.thenCompose(cacheOk -> {
if (cacheOk) {
scheduler.schedule(() -> { // ← 直接用调度器延迟
saveToPersist(table, key, dataWithKey);
}, ttl, TimeUnit.SECONDS);
}, finalTTL, TimeUnit.SECONDS);
}
return CompletableFuture.completedFuture(cacheOk);
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,6 @@ private DatabaseConfig loadDatabaseConfig() {
Map<String, Object> cachingSection = pluginConfig.getSection("caching").getAllMap();
if (!cachingSection.isEmpty()) {
config.getCaching().setDefaultTTL(getInt(cachingSection, "defaultTTL", 3600));
config.getCaching().setPlayerDataTTL(getInt(cachingSection, "playerDataTTL", 7200));
config.getCaching().setAutoRefresh(getBoolean(cachingSection, "autoRefresh", true));
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import cn.nukkit.event.Listener;
import cn.nukkit.event.player.PlayerJoinEvent;
import cn.nukkit.event.player.PlayerQuitEvent;
import com.yirankuma.yrdatabase.api.CacheStrategy;
import com.yirankuma.yrdatabase.api.DatabaseManager;
import com.yirankuma.yrdatabase.api.event.SessionReason;
import com.yirankuma.yrdatabase.nukkit.YRDatabaseNukkit;
Expand Down Expand Up @@ -69,7 +70,7 @@ public void onPlayerJoin(PlayerJoinEvent event) {
sessionBridge.triggerLocalJoin(uuid.toString(), playerName);
}

db.get("player_sessions", uuid.toString())
db.get("player_sessions", uuid.toString(),30)
.thenAccept(result -> {
if (result.isPresent()) {
Map<String, Object> data = result.get();
Expand Down Expand Up @@ -131,7 +132,7 @@ public void onPlayerQuit(PlayerQuitEvent event) {
sessionData.put("z", player.getZ());
sessionData.put("world", player.getLevel().getName());

db.set("player_sessions", uuid.toString(), sessionData)
db.set("player_sessions", uuid.toString(), sessionData, CacheStrategy.PERSIST_ONLY)
.thenAccept(success -> {
if (success) {
plugin.getLogger().debug("Cached session data for " + playerName);
Expand All @@ -156,7 +157,7 @@ private void createNewSession(UUID uuid, String playerName) {
sessionData.put("firstJoin", System.currentTimeMillis());
sessionData.put("lastSeen", System.currentTimeMillis());

db.set("player_sessions", uuid.toString(), sessionData)
db.set("player_sessions", uuid.toString(), sessionData,CacheStrategy.PERSIST_ONLY)
.thenAccept(success -> {
if (success) {
plugin.getLogger().debug("Created new session for " + playerName);
Expand All @@ -175,7 +176,7 @@ private void recordPlayerEvent(UUID uuid, String playerName, String eventType) {
eventData.put("timestamp", System.currentTimeMillis());
eventData.put("server", plugin.getServer().getName());

db.set("player_events", uuid.toString(), eventData)
db.set("player_events", uuid.toString(), eventData,CacheStrategy.PERSIST_ONLY)
.exceptionally(e -> {
plugin.getLogger().error("Failed to record event " + eventType + " for " + playerName, e);
return null;
Expand Down
1 change: 0 additions & 1 deletion yrdatabase-nukkit/src/main/resources/config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,6 @@ persist:
# Caching settings
caching:
defaultTTL: 3600 # seconds
playerDataTTL: 7200 # seconds
autoRefresh: true

# Session management
Expand Down