NeoPlayerSync
你在 Velocity 等代理后面运行多个 NeoForge 服务器。每个服务器都保留着每位玩家的独立副本,因此当玩家切换服务器时,他们将以空背包的状态出现。
NeoPlayerSync 在 PostgreSQL 数据库中为每位玩家保存一份副本,供所有服务器共享。当玩家切换服务器时,他们会携带自己的角色数据一起移动。
随玩家同步的数据
- 物品栏、护甲、副手和末影箱
- 生命值、饥饿值和药水效果
- 经验值和配方书
- 你的模组附加的玩家附件(player attachments)和持久化数据,例如 Curios 槽位
- 进度和统计数据,如果你启用了
sync_advancements 或 sync_statistics
位置和重生点保留在每个服务器上。
有些模组将玩家数据存储在世界存档中而不是玩家身上。这些数据会留在原处,直到模组作者将其移至玩家身上(参见 For mod developers)或 NeoPlayerSync 添加对该模组的支持。
所需条件
玩家和代理无需安装任何内容。
设置
1. 创建数据库。 在 PostgreSQL 中,创建一个空数据库并指定一个拥有者用户:
CREATE USER minecraft WITH PASSWORD 'pick-a-strong-password';
CREATE DATABASE minecraft OWNER minecraft;
NeoPlayerSync 会自动创建其所需的表。
2. 安装模组。 将 jar 文件放入每个服务器的 mods 文件夹中。启动每个服务器一次然后停止。这将生成 config/neoplayersync.toml。
3. 填写配置 在每个服务器上:
enabled = true
host = "10.0.0.5" # 你的数据库地址
port = 5432
database = "minecraft"
user = "minecraft"
password = "pick-a-strong-password"
require_ssl = true # 仅当数据库与服务器在同一台机器上运行时设为 false
ssl_root_cert = "" # 见下文“检查数据库证书”
server_name = "lobby" // 任意名称;数据库将其显示为玩家当前所在的服务器
sync_advancements = false # 设为 true 可使进度随玩家同步
sync_statistics = false # 设为 true 可使统计数据随玩家同步
docs/default-config.toml 解释了每个设置的含义。更改配置需要重启服务器。
该文件包含你的数据库密码。请勿将其放入你要分享的整合包中。
4. 启动你的服务器。 每个日志应显示:
NeoPlayerSync is storing players in Postgres.
你可以将模组添加到已有玩家的网络中。玩家在首次被服务器保存时,其当前角色数据将存入数据库。
保持服务器版本一致
- 所有服务器使用相同的 Minecraft 版本。 如果服务器检测到来自更高版本的存档角色,它将拒绝加载。
- 所有服务器安装相同的模组。 如果服务器缺少玩家使用的模组,它将拒绝玩家加入,从而导致该模组的物品和数据不会丢失。若要允许玩家加入模组较少的服务器(如大厅),请在那里设置
enabled = false。
- 所有服务器使用相同的 NeoPlayerSync 版本。 请同时更新所有服务器。新版本可能会升级数据库表,而旧版本随后将无法启动。正在运行的服务器将继续正常工作。
- 所有服务器使用相同的
sync_advancements 和 sync_statistics 设置。 如果为已包含玩家的网络开启其中一项,第一个保存玩家的服务器将决定玩家保留哪些数据。其他服务器中的副本将被替换。
设置为 enabled = false 的服务器将保留每位玩家的独立副本,且不接触数据库。
当服务器无法启动时
如果服务器无法连接到数据库,它将拒绝启动,以防止玩家加载旧的角色副本。如果 config/neoplayersync.toml 损坏,即使是在服务器运行时损坏,它也会拒绝启动。此时 NeoForge 会恢复默认值(这会关闭同步功能),并将你的文件保存为 config/neoplayersync-1.toml.bak。修复该副本并将其放回原位,或者如果你打算关闭同步,可以删除它。
命令
两者都需要操作员权限级别 2。
/nps(或 /nps health)用于检查数据库状态。它会显示数据库响应耗时、本服务器持有的玩家数量以及等待发送的存档数量。超时时间为 20 秒。
/nps sync 立即保存本服务器上所有玩家的数据,并等待数据库确认接收完毕。它会报告耗时,或报告保存失败/耗时超过 20 秒。服务器会对慢速保存进行重试。在繁忙的服务器上,这可能会导致短暂的卡顿。
工作原理
可以将数据库想象成一个图书馆,其中每位玩家只有一份副本。服务器在玩家加入时“借出”其角色,并在玩家离开时“归还”。
- 玩家加入。服务器从数据库借出其角色并加载。
- 在游戏过程中,服务器会在其物品栏发生变化后约一秒、每分钟一次,以及在玩家重生或离开时,将角色数据发回。如果没有变化,则不发送任何内容。
- 玩家切换服务器。旧服务器最后一次发送角色数据并归还。新服务器等待接收,然后借出该角色。
同一时间只能有一个服务器借用某位玩家,因此两个服务器永远不会互相覆盖。
如果服务器崩溃,下一个服务器会等待约 15 秒以确保崩溃的服务器已消失,然后接管该玩家。玩家将损失最多一秒的物品栏变化数据和最多一分钟的其他所有数据。
检查数据库证书
在私有网络上,require_ssl = true 就足够了。但在互联网或共享云网络上,中间人可能会伪装成你的数据库并窃取密码。为防止这种情况,请为每台服务器提供签署你数据库证书的权威机构的 PEM 证书:
ssl_root_cert = "config/postgres-ca.crt"
数据库的证书必须与 host 中的地址名称一致。相对路径从服务器文件夹开始计算。在 Windows 上,请使用正斜杠,例如 "C:/certs/ca.crt"。反斜杠会导致配置文件出错。
数据库连接
每个服务器会保持 3 个到 PostgreSQL 的连接。一个用于在玩家加入时加载其数据并响应其他模组的读取请求,一个用于发送玩家的存档数据,另一个用于续期服务器对已拥有玩家的持有权。请将 PostgreSQL 中的 max_connections 设置为至少每后端(backend)3 个连接,并为使用数据库的其他内容预留空间。
给模组开发者
大多数模组无需任何更改。NeoPlayerSync 会随玩家一起迁移你的玩家附加数据(player attachments)和持久化数据。它会留在世界存档(SavedData)中或玩家文件下你自己键名下的任何内容不动。若要使数据跟随玩家迁移,请将其保存在玩家附加数据中。
有两种情况需要你添加少量代码。
立即保存重要变更
常规存档每分钟执行一次。当玩家获得某些不应因崩溃而丢失的内容(例如解锁或稀有奖励)时,请立即保存:
player.level().getServer().getPlayerList().getPlayerIo().save(player);
这是标准的 Minecraft 代码,因此你不需要依赖 NeoPlayerSync。
修复以游戏刻存储的计时器
假设你将冷却时间存储为“在游戏刻 5,000,600 结束”。每个服务器都从其自身启动开始计数刻数,因此该数字在下一个服务器上毫无意义。玩家可能会等待数小时或直接跳过冷却时间。
当 NeoPlayerSync 从数据库加载玩家时,它会告知你存档的时间长短。在 PlayerEvent.LoadFromFile 期间,玩家的持久化数据中包含一个名为 neoplayersync:restored 的结构体(compound):
| 字段 |
含义 |
saved_game_time |
旧服务器保存玩家时的游戏刻数 |
elapsed_millis |
自那次保存以来的真实时间(毫秒) |
将你的截止时间偏移到此服务器的时钟上:
@SubscribeEvent
public static void onLoad(PlayerEvent.LoadFromFile event) {
event.getEntity().getPersistentData().getCompound("neoplayersync:restored").ifPresent(restored -> {
long savedGameTime = restored.getLongOr("saved_game_time", 0L);
long elapsedMillis = restored.getLongOr("elapsed_millis", 0L);
long now = event.getEntity().level().getServer().overworld().getGameTime();
long shift = now - savedGameTime - elapsedMillis / 50;
// 将你存储为游戏刻数的所有截止时间加上此偏移量。
});
}
- 以正常优先级监听。NeoPlayerSync 会在
HIGHEST 优先级添加标签,并在 LOWEST 优先级移除它。
- 该标签每次加入最多出现一次。玩家的首次加载不会带有此标签。
- 读取该标签;不要移除它。其他模组可能需要它。
若未安装 NeoPlayerSync,该标签永远不会出现,你的监听器也不会执行任何操作。
你可以像上面那样自己输入名称,或使用 API 中的 NeoPlayerSyncApi.RESTORED_TAG、SAVED_GAME_TIME 和 ELAPSED_MILLIS。编译器会将这些名称复制到你的模组中,因此即使未安装 NeoPlayerSync 它们也能正常工作,且无需进行 isLoaded 检查。
读取不在此处的玩家
NeoPlayerSyncApi 可从数据库读取玩家的存档,即使该玩家离线或在另一台服务器上。你可以用它来实现显示某人统计信息的命令。读取操作不会锁定玩家,因此他们仍可加入任何服务器。
将其添加到你的 build.gradle 中。该 API 需要 NeoPlayerSync 1.2.0 或更高版本:
repositories {
maven {
url = 'https://api.modrinth.com/maven'
content { includeGroup 'maven.modrinth' }
}
}
dependencies {
compileOnly 'maven.modrinth:neoplayersync:1.2.0'
}
compileOnly 允许你的模组在没有 NeoPlayerSync 的情况下运行。如果你的模组需要它,请使用 implementation,并在你的 neoforge.mods.toml 中将 neoplayersync 标记为必需。
NeoPlayerSyncApi 位于 dev.xshirae.neoplayersync.api 包中,包含两个调用:
| 调用 |
返回值 |
isDatabaseEnabled() |
如果此服务器将玩家存储在数据库中则返回 true。若配置为 enabled = false、在单人或局域网模式下,或服务器未运行时返回 false |
readStoredPlayer(UUID) |
一个 CompletableFuture<Optional<CompoundTag>>,其中包含玩家的存档文件。该文件会像原版升级 .dat 文件一样升级到当前 Minecraft 版本 |
- 请在服务器线程上调用它。你的回调也会在该线程上运行。
- 空结果表示数据库尚无任何该玩家的数据。如果他们自你开启数据库以来从未加入过,他们的存档可能仍位于某台服务器的
playerdata/<uuid>.dat 中。
- 如果
isDatabaseEnabled() 返回 false,请改为读取 playerdata/<uuid>.dat。
- 另一台服务器上的玩家可能拥有多达一分钟的、数据库尚未拥有的变更。对于在你服务器上的玩家,请直接读取实时玩家。
- 结果为只读。
- 仅在有人请求时读取一名玩家。一次性读取所有人会导致正在加入的玩家等待。
当读取失败时,Future 将以说明原因的 IllegalStateException 失败。你永远不会收到空白的玩家数据。当数据库关闭或服务器未运行、较新版本的 NeoPlayerSync 或 Minecraft 保存了该玩家、存档损坏,或数据库出错或耗时超过 20 秒时,读取会失败。
为了保持 NeoPlayerSync 的可选性,请将你的 API 调用放在单独的类中,并且仅在 ModList.get().isLoaded("neoplayersync") 返回 true 后调用它。Java 会在首次使用时加载该类,因此即使未安装 NeoPlayerSync,你的模组仍能运行:
final class StoredPlayers {
static CompletableFuture<Optional<CompoundTag>> read(UUID playerId) {
return NeoPlayerSyncApi.readStoredPlayer(playerId);
}
static boolean databaseEnabled() {
return NeoPlayerSyncApi.isDatabaseEnabled();
}
}
boolean useDatabase = ModList.get().isLoaded("neoplayersync") && StoredPlayers.databaseEnabled();
只有 api 包和 neoplayersync:restored 标签是公开的。其余部分在任意版本中都可能发生变化。NeoPlayerSyncApi.API_VERSION 的值为 1,仅当变更会破坏为旧 API 构建的模组时才会递增。你的模组会在运行时读取该值,因此你可以在调用任何较新的内容之前进行检查。
构建
你需要 Java 25。在 Windows 上:
.\tools\run-gradle.ps1 build
该脚本使用 JAVA_HOME,或解压到 tools/java25 中的 JDK。jar 文件位于 build/libs。
某些测试需要数据库。解压 PostgreSQL Windows 二进制文件,确保存在 tools/postgres/pgsql/bin,然后执行:
.\tools\test-postgres.ps1 start
.\tools\run-gradle.ps1 build
.\tools\run-gradle.ps1 runGameTestServer --project-prop=includeGameTests=true
.\tools\test-postgres.ps1 stop
test-postgres.ps1 会在 127.0.0.1:5433 上运行一个一次性数据库。如果没有它,数据库测试将自动跳过。
测试基于 26.1.2 版本运行。若要测试更新的版本线,请添加 -Pmc=26.2 或 -Pmc=26.3。请保留引号,否则 PowerShell 会在点号处分割版本号:
.\tools\run-gradle.ps1 runGameTestServer '-Pmc=26.3' --project-prop=includeGameTests=true
许可证
NeoPlayerSync 是基于 GNU 通用公共许可证,第 2 版 的自由软件,或者根据你的选择,采用任何后续版本(GPL-2.0-or-later)。
NeoPlayerSync
You run several NeoForge servers behind a proxy like Velocity. Each server keeps its own copy of every player, so a player who switches servers arrives with an empty inventory.
NeoPlayerSync keeps one copy of each player in a PostgreSQL database that all your servers share. When a player switches servers, they bring their character with them.
What travels with the player
- inventory, armor, off hand and ender chest
- health, hunger and potion effects
- experience and the recipe book
- your mods' player attachments and persistent data, such as Curios slots
- advancements and statistics, if you turn on
sync_advancements or sync_statistics
Position and spawn point stay on each server.
Some mods store player data in the world save instead of on the player. That data stays behind until the mod's author moves it onto the player (see For mod developers) or NeoPlayerSync adds support for that mod.
What you need
- Kotlin for Forge 6.4.0
- a PostgreSQL server (we test with 17.6)
- a proxy such as Velocity, with player forwarding set up
- a mod that lets NeoForge accept that forwarding, such as Proxy Compatible Forge
Players and the proxy don't install anything.
Setup
1. Make a database. In PostgreSQL, create an empty database and a user who owns it:
CREATE USER minecraft WITH PASSWORD 'pick-a-strong-password';
CREATE DATABASE minecraft OWNER minecraft;
NeoPlayerSync creates its own tables.
2. Install the mod. Put the jar in the mods folder of each server. Start each server once and stop it. This creates config/neoplayersync.toml.
3. Fill in the config on each server:
enabled = true
host = "10.0.0.5" # your database's address
port = 5432
database = "minecraft"
user = "minecraft"
password = "pick-a-strong-password"
require_ssl = true # set false only if the database runs on the same machine
ssl_root_cert = "" # see "Check the database's certificate" below
server_name = "lobby" # any name; the database shows it as the player's current server
sync_advancements = false # true moves advancements with the player
sync_statistics = false # true moves statistics with the player
docs/default-config.toml explains every setting. Changes need a restart.
The file holds your database password. Keep it out of modpacks you share.
4. Start your servers. Each log should show:
NeoPlayerSync is storing players in Postgres.
You can add the mod to a network that already has players. A player's current character goes into the database the first time a server saves them.
Keep your servers matched
- Same Minecraft version everywhere. A server refuses a character saved by a newer version.
- Same mods everywhere. A server missing a mod your players use refuses them, so their items and data from that mod don't get lost. To let players join a server with fewer mods, such as a hub, set
enabled = false there.
- Same NeoPlayerSync version everywhere. Update all servers together. A newer version may upgrade the database tables, and an older one then refuses to start. Servers already running keep working.
- Same
sync_advancements and sync_statistics everywhere. If you turn one on for a network that already has players, the first server to save a player decides what they keep. Other servers' copies get replaced.
A server with enabled = false keeps its own separate copy of each player and never touches the database.
When a server won't start
A server refuses to start if it can't reach the database, so players never load an old copy of their character. It also refuses if config/neoplayersync.toml is broken, even if it broke while the server ran. NeoForge then swaps in defaults, which turn sync off, and saves your file as config/neoplayersync-1.toml.bak. Fix that copy and put it back, or delete it if you meant to turn sync off.
Commands
Both need operator permission level 2.
/nps (or /nps health) checks the database. It shows how long the database took to answer, how many players this server holds, and how many saves are waiting to go out. It gives up after 20 seconds.
/nps sync saves every player on this server now and waits until the database has them all. It reports how long that took, or that a save failed or took more than 20 seconds. The server keeps retrying a slow save. On a busy server it can cause a short lag spike.
How it works
Think of the database as a library with one copy of each player. A server borrows a player when they join and returns them when they leave.
- A player joins. The server borrows their character from the database and loads it.
- While they play, the server sends their character back about a second after their inventory changes, once a minute, and when they respawn or leave. If nothing changed, it sends nothing.
- The player switches servers. The old server sends the character one last time and returns it. The new server waits for that, then borrows it.
Only one server can borrow a player at a time, so two servers never overwrite each other.
If a server crashes, the next server waits about 15 seconds to be sure the crashed one is gone, then takes the player. The player loses up to a second of inventory changes and up to a minute of everything else.
Check the database's certificate
On a private network, require_ssl = true is enough. Over the internet or a shared cloud network, someone in between could pretend to be your database and steal the password. To prevent that, give each server the PEM certificate of the authority that signed your database's certificate:
ssl_root_cert = "config/postgres-ca.crt"
The database's certificate must name the address in host. A relative path starts from the server folder. On Windows, use forward slashes, like "C:/certs/ca.crt". A backslash breaks the config file.
Database connections
Each server keeps 3 connections open to PostgreSQL. One loads players as they join and answers other mods' reads, one sends their saves, and one renews the server's hold on the players it has. Set max_connections in PostgreSQL to at least 3 per backend, plus room for anything else that uses the database.
For mod developers
Most mods need no changes. NeoPlayerSync moves your player attachments and persistent data with the player. It leaves behind anything in a world save (SavedData) or under your own key in the player file. To make data travel, keep it in a player attachment.
Two cases need a few lines from you.
Save important changes right away
The regular save comes once a minute. When a player earns something they must not lose to a crash, like an unlock or a rare reward, save them at once:
player.level().getServer().getPlayerList().getPlayerIo().save(player);
This is plain Minecraft code, so you need no dependency on NeoPlayerSync.
Fix timers stored as game ticks
Say you store a cooldown as "ends at game tick 5,000,600". Each server counts ticks from its own start, so that number means nothing on the next server. The player might wait hours or skip the cooldown.
When NeoPlayerSync loads a player from the database, it tells you how old the save is. During PlayerEvent.LoadFromFile, the player's persistent data holds a compound named neoplayersync:restored:
| Field |
Meaning |
saved_game_time |
the old server's game tick when it saved the player |
elapsed_millis |
real time since that save, in milliseconds |
Shift your deadlines onto this server's clock:
@SubscribeEvent
public static void onLoad(PlayerEvent.LoadFromFile event) {
event.getEntity().getPersistentData().getCompound("neoplayersync:restored").ifPresent(restored -> {
long savedGameTime = restored.getLongOr("saved_game_time", 0L);
long elapsedMillis = restored.getLongOr("elapsed_millis", 0L);
long now = event.getEntity().level().getServer().overworld().getGameTime();
long shift = now - savedGameTime - elapsedMillis / 50;
// Add shift to every deadline you stored as a game tick.
});
}
- Listen at normal priority. NeoPlayerSync adds the tag at
HIGHEST and removes it at LOWEST.
- The tag appears at most once per join. A player's first load gets no tag.
- Read the tag; don't remove it. Other mods may need it.
Without NeoPlayerSync installed, the tag never appears and your listener does nothing.
You can type the names yourself, as above, or use NeoPlayerSyncApi.RESTORED_TAG, SAVED_GAME_TIME and ELAPSED_MILLIS from the API. Your compiler copies those names into your mod, so they work without NeoPlayerSync installed and need no isLoaded check.
Read a player who isn't here
NeoPlayerSyncApi reads a player's save from the database, even when that player is offline or on another server. You could use it for a command that shows someone's stats. Reading doesn't lock the player, so they can still join any server.
Add it to your build.gradle. The API needs NeoPlayerSync 1.2.0 or newer:
repositories {
maven {
url = 'https://api.modrinth.com/maven'
content { includeGroup 'maven.modrinth' }
}
}
dependencies {
compileOnly 'maven.modrinth:neoplayersync:1.2.0'
}
compileOnly lets your mod run without NeoPlayerSync. If your mod needs it, use implementation and mark neoplayersync as required in your neoforge.mods.toml.
NeoPlayerSyncApi lives in dev.xshirae.neoplayersync.api and has two calls:
| Call |
Returns |
isDatabaseEnabled() |
true if this server stores players in the database. false with enabled = false, in singleplayer or LAN, or while the server isn't running |
readStoredPlayer(UUID) |
a CompletableFuture<Optional<CompoundTag>> holding the player's save file, upgraded to this Minecraft version the way vanilla upgrades a .dat file |
- Call it on the server thread. Your callbacks run there too.
- An empty result means the database has nothing for that player yet. If they haven't joined since you turned the database on, their save may still be in
playerdata/<uuid>.dat on one of your servers.
- If
isDatabaseEnabled() is false, read playerdata/<uuid>.dat instead.
- A player on another server may have up to a minute of changes the database doesn't have yet. For a player on your server, read the live player.
- The result is read-only.
- Read one player when someone asks. Reading everyone at once makes joining players wait.
When a read fails, the future fails with an IllegalStateException that says why. You never get a blank player. Reads fail when the database is off or the server isn't running, a newer NeoPlayerSync or Minecraft saved the player, the save is broken, or the database errors or takes over 20 seconds.
To keep NeoPlayerSync optional, put your API calls in a class of their own and call it only after ModList.get().isLoaded("neoplayersync") returns true. Java loads that class on its first use, so your mod still runs without NeoPlayerSync:
final class StoredPlayers {
static CompletableFuture<Optional<CompoundTag>> read(UUID playerId) {
return NeoPlayerSyncApi.readStoredPlayer(playerId);
}
static boolean databaseEnabled() {
return NeoPlayerSyncApi.isDatabaseEnabled();
}
}
boolean useDatabase = ModList.get().isLoaded("neoplayersync") && StoredPlayers.databaseEnabled();
Only the api package and the neoplayersync:restored tag are public. The rest can change in any release. NeoPlayerSyncApi.API_VERSION is 1 and goes up only when a change breaks mods built for an older API. Your mod reads it at runtime, so you can check it before calling anything newer.
Building
You need Java 25. On Windows:
.\tools\run-gradle.ps1 build
The script uses JAVA_HOME, or a JDK unpacked into tools/java25. The jar lands in build/libs.
Some tests need a database. Unpack the PostgreSQL Windows binaries so that tools/postgres/pgsql/bin exists, then:
.\tools\test-postgres.ps1 start
.\tools\run-gradle.ps1 build
.\tools\run-gradle.ps1 runGameTestServer --project-prop=includeGameTests=true
.\tools\test-postgres.ps1 stop
test-postgres.ps1 runs a throwaway database on 127.0.0.1:5433. Without it, the database tests skip themselves.
Tests run on 26.1.2. To test a newer line, add -Pmc=26.2 or -Pmc=26.3. Keep the quotes, or PowerShell splits the version at the dot:
.\tools\run-gradle.ps1 runGameTestServer '-Pmc=26.3' --project-prop=includeGameTests=true
License
NeoPlayerSync is free software under the GNU General Public License, version 2 or, at your option, any later version (GPL-2.0-or-later).
评论 0
登录后参与评分
还没有评论,来抢沙发吧