Saltar al contenido

Ejemplos

Guardar tus propios datos

Guarda y actualiza un registro versionado por jugador con PersistenceService y compare-and-set, sin bloquear el servidor.

KillsStore.javaJava
import java.nio.charset.StandardCharsets;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import net.sofycore.api.storage.PersistenceService;
import net.sofycore.api.storage.StoredRecord;

final class KillsStore {
    private static final String NS = "myplugin-kills";
    private final PersistenceService store;

    KillsStore(PersistenceService store) { this.store = store; }

    CompletableFuture<Boolean> increment(UUID player) {
        String key = player.toString();
        return store.getAsync(NS, key).thenCompose(record -> {
            long revision = record.map(StoredRecord::revision).orElse(-1L);
            int kills = record.map(r -> Integer.parseInt(new String(r.payload(), StandardCharsets.UTF_8))).orElse(0);
            byte[] next = String.valueOf(kills + 1).getBytes(StandardCharsets.UTF_8);
            return store.putAsync(NS, key, revision, next); // false = otro escribió antes
        });
    }
}

Si putAsync devuelve false, vuelve a leer y reintenta un número limitado de veces. No reintentes a ciegas tras un error de I/O: la escritura puede haberse realizado.