feat: 允许数据库独立于core配置

This commit is contained in:
2023-08-12 12:59:52 +08:00
parent 11327d368e
commit fa7f07657f
12 changed files with 251 additions and 63 deletions

View File

@@ -6,16 +6,15 @@ dependencies {
apiShade project(":ball-common") transitive false
//noinspection VulnerableLibrariesLocal
compileOnly 'org.spigotmc:spigot-api:1.19.4-R0.1-SNAPSHOT'
compileOnly 'org.spigotmc:spigot-api:1.20.1-R0.1-SNAPSHOT'
compileOnly "cn.hamster3.mc.plugin:core-bukkit:${hamster_core_version}"
compileOnly "me.clip:placeholderapi:2.11.2" transitive false
}
processResources {
inputs.property "version", project.version
filesMatching("plugin.yml") {
expand "version": project.version
expand(project.properties)
}
duplicatesStrategy(DuplicatesStrategy.EXCLUDE)
}
@@ -37,6 +36,6 @@ tasks.register("shadowJar", Jar) {
it.isDirectory() ? it : zipTree(it)
}
])
destinationDir(rootProject.buildDir)
destinationDirectory = rootProject.buildDir
}
tasks.build.dependsOn(shadowJar)

View File

@@ -2,20 +2,25 @@ package cn.hamster3.mc.plugin.ball.bukkit.api;
import cn.hamster3.mc.plugin.ball.bukkit.HamsterBallPlugin;
import cn.hamster3.mc.plugin.ball.bukkit.listener.BallBukkitListener;
import cn.hamster3.mc.plugin.ball.bukkit.util.BallBukkitUtils;
import cn.hamster3.mc.plugin.ball.common.api.BallAPI;
import cn.hamster3.mc.plugin.ball.common.config.BallConfig;
import cn.hamster3.mc.plugin.ball.common.entity.BallServerInfo;
import cn.hamster3.mc.plugin.ball.common.entity.BallServerType;
import cn.hamster3.mc.plugin.ball.common.listener.BallDebugListener;
import cn.hamster3.mc.plugin.core.common.api.CoreAPI;
import org.bukkit.Bukkit;
import org.bukkit.configuration.file.FileConfiguration;
import org.jetbrains.annotations.NotNull;
import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.Map;
import java.util.logging.Logger;
public class BallBukkitAPI extends BallAPI {
private DataSource datasource;
public BallBukkitAPI(@NotNull BallConfig config) {
super(config);
}
@@ -58,12 +63,15 @@ public class BallBukkitAPI extends BallAPI {
String.valueOf(pluginConfig.getInt("ball-server.event-loop-thread", 2))));
BallConfig config = new BallConfig(serverInfo, serverHost, serverPort, eventLoopThread);
instance = new BallBukkitAPI(config);
BallBukkitAPI apiInstance = new BallBukkitAPI(config);
apiInstance.datasource = BallBukkitUtils.getDataSource(pluginConfig.getConfigurationSection("datasource"));
instance.addListener(BallBukkitListener.INSTANCE);
apiInstance.addListener(BallBukkitListener.INSTANCE);
if (pluginConfig.getBoolean("debug", false)) {
instance.addListener(BallDebugListener.INSTANCE);
apiInstance.addListener(BallDebugListener.INSTANCE);
}
instance = apiInstance;
}
@Override
@@ -80,4 +88,9 @@ public class BallBukkitAPI extends BallAPI {
public @NotNull Logger getLogger() {
return HamsterBallPlugin.getInstance().getLogger();
}
@Override
public @NotNull DataSource getDatasource() {
return datasource == null ? CoreAPI.getInstance().getDataSource() : datasource;
}
}

View File

@@ -0,0 +1,41 @@
package cn.hamster3.mc.plugin.ball.bukkit.util;
import cn.hamster3.mc.plugin.core.lib.com.zaxxer.hikari.HikariConfig;
import cn.hamster3.mc.plugin.core.lib.com.zaxxer.hikari.HikariDataSource;
import org.bukkit.configuration.ConfigurationSection;
import org.jetbrains.annotations.Nullable;
import javax.sql.DataSource;
public final class BallBukkitUtils {
private BallBukkitUtils() {
}
@Nullable
public static DataSource getDataSource(@Nullable ConfigurationSection datasourceConfig) {
if (datasourceConfig == null) {
return null;
}
try {
HikariConfig hikariConfig = new HikariConfig();
String driver = datasourceConfig.getString("driver");
hikariConfig.setDriverClassName(driver);
hikariConfig.setJdbcUrl(datasourceConfig.getString("url"));
hikariConfig.setUsername(datasourceConfig.getString("username"));
hikariConfig.setPassword(datasourceConfig.getString("password"));
hikariConfig.setMaximumPoolSize(datasourceConfig.getInt("maximum-pool-size", 3));
hikariConfig.setMinimumIdle(datasourceConfig.getInt("minimum-idle", 1));
long keepAliveTime = datasourceConfig.getLong("keep-alive-time", 0);
if (keepAliveTime > 5000) {
hikariConfig.setKeepaliveTime(keepAliveTime);
}
hikariConfig.setIdleTimeout(datasourceConfig.getLong("idle-timeout", 10 * 60 * 1000));
hikariConfig.setMaxLifetime(datasourceConfig.getLong("max-lifetime", 30 * 60 * 1000));
hikariConfig.setValidationTimeout(datasourceConfig.getLong("validation-timeout", 5000));
hikariConfig.setPoolName("HamsterBall-Pool");
return new HikariDataSource(hikariConfig);
} catch (Exception | Error e) {
return null;
}
}
}

View File

@@ -25,3 +25,38 @@ server-info:
# 当前子服的内网端口
# 不填则自动获取 server.properties 文件中的设置
# port: 25577
# 数据库连接池配置
# 如果注释该选项则默认使用 HamsterCore 中的连接池配置
#datasource:
# # 数据库链接驱动地址
# driver: "com.mysql.jdbc.Driver"
# # 数据库链接填写格式:
# # jdbc:mysql://{数据库地址}:{数据库端口}/{使用的库名}?参数
# # 除非你知道自己在做什么,否则不建议随意更改参数
# url: "jdbc:mysql://sql.hamster3.cn:3306/Test1?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8&autoReconnect=true&useSSL=false&allowPublicKeyRetrieval=true"
# # 用户名
# username: "Test"
# # 密码
# password: "Test123.."
# # 最小闲置链接数
# # 推荐值1~3
# minimum-idle: 0
# # 最大链接数
# # 推荐值不低于3
# maximum-pool-size: 3
# # 保持连接池可用的间隔
# # 除非你的服务器数据库连接经常断开,否则不建议启用该选项
# # 单位:毫秒
# # 默认值为0禁用
# keep-alive-time: 0
# # 连接闲置回收时间
# # 单位:毫秒
# # 推荐值60000010分钟
# idle-timeout: 600000
# # 链接最长存活时间
# # 单位:毫秒
# max-lifetime: 1800000
# # 验证连接存活的超时时间
# # 单位:毫秒
# validation-timeout: 5000

View File

@@ -6,15 +6,14 @@ dependencies {
apiShade project(":ball-common") transitive false
//noinspection VulnerableLibrariesLocal
compileOnly 'net.md-5:bungeecord-api:1.19-R0.1-SNAPSHOT' exclude group: 'io.netty'
compileOnly 'net.md-5:bungeecord-api:1.20-R0.1-SNAPSHOT' exclude group: 'io.netty'
compileOnly "cn.hamster3.mc.plugin:core-bungeecord:${hamster_core_version}"
}
processResources {
inputs.property "version", project.version
filesMatching("bungee.yml") {
expand "version": project.version
expand(project.properties)
}
duplicatesStrategy(DuplicatesStrategy.EXCLUDE)
}
@@ -36,6 +35,6 @@ tasks.register("shadowJar", Jar) {
it.isDirectory() ? it : zipTree(it)
}
])
destinationDir(rootProject.buildDir)
destinationDirectory = rootProject.buildDir
}
tasks.build.dependsOn(shadowJar)

View File

@@ -7,15 +7,20 @@ import cn.hamster3.mc.plugin.ball.common.entity.BallServerType;
import cn.hamster3.mc.plugin.ball.common.listener.BallDebugListener;
import cn.hamster3.mc.plugin.core.bungee.HamsterBallPlugin;
import cn.hamster3.mc.plugin.core.bungee.listener.BallBungeeCordListener;
import cn.hamster3.mc.plugin.core.bungee.util.BallBungeeCordUtils;
import cn.hamster3.mc.plugin.core.bungee.util.CoreBungeeCordUtils;
import cn.hamster3.mc.plugin.core.common.api.CoreAPI;
import net.md_5.bungee.config.Configuration;
import org.jetbrains.annotations.NotNull;
import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.Map;
import java.util.logging.Logger;
public class BallBungeeCordAPI extends BallAPI {
private DataSource datasource;
public BallBungeeCordAPI(@NotNull BallConfig config) {
super(config);
}
@@ -56,12 +61,14 @@ public class BallBungeeCordAPI extends BallAPI {
String.valueOf(pluginConfig.getInt("ball-server.event-loop-thread", 2))));
BallConfig config = new BallConfig(serverInfo, serverHost, serverPort, eventLoopThread);
instance = new BallBungeeCordAPI(config);
BallBungeeCordAPI apiInstance = new BallBungeeCordAPI(config);
apiInstance.datasource = BallBungeeCordUtils.getDataSource(pluginConfig.getSection("datasource"));
instance.addListener(BallBungeeCordListener.INSTANCE);
apiInstance.addListener(BallBungeeCordListener.INSTANCE);
if (pluginConfig.getBoolean("debug", false)) {
instance.addListener(BallDebugListener.INSTANCE);
apiInstance.addListener(BallDebugListener.INSTANCE);
}
instance = apiInstance;
}
@Override
@@ -78,4 +85,9 @@ public class BallBungeeCordAPI extends BallAPI {
public @NotNull Logger getLogger() {
return HamsterBallPlugin.getInstance().getLogger();
}
@Override
public @NotNull DataSource getDatasource() {
return datasource == null ? CoreAPI.getInstance().getDataSource() : datasource;
}
}

View File

@@ -3,12 +3,16 @@ package cn.hamster3.mc.plugin.core.bungee.util;
import cn.hamster3.mc.plugin.ball.common.api.BallAPI;
import cn.hamster3.mc.plugin.ball.common.entity.BallPlayerInfo;
import cn.hamster3.mc.plugin.ball.common.event.player.BallPlayerInfoUpdateEvent;
import cn.hamster3.mc.plugin.core.common.api.CoreAPI;
import cn.hamster3.mc.plugin.core.common.util.CoreUtils;
import cn.hamster3.mc.plugin.core.lib.com.zaxxer.hikari.HikariConfig;
import cn.hamster3.mc.plugin.core.lib.com.zaxxer.hikari.HikariDataSource;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import net.md_5.bungee.api.connection.Server;
import net.md_5.bungee.config.Configuration;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
@@ -31,15 +35,17 @@ public final class BallBungeeCordUtils {
public static void uploadPlayerInfo(@NotNull BallPlayerInfo playerInfo) {
CoreUtils.WORKER_EXECUTOR.execute(() -> {
try (Connection connection = CoreAPI.getInstance().getConnection()) {
PreparedStatement statement = connection.prepareStatement("REPLACE INTO `hamster_ball_player_info` VALUES(?, ?, ?, ?, ?);");
statement.setString(1, playerInfo.getUuid().toString());
statement.setString(2, playerInfo.getName());
statement.setString(3, playerInfo.getGameServer());
statement.setString(4, playerInfo.getProxyServer());
statement.setBoolean(5, playerInfo.isOnline());
statement.executeUpdate();
statement.close();
try (Connection connection = BallAPI.getInstance().getDatasource().getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(
"REPLACE INTO `hamster_ball_player_info` VALUES(?, ?, ?, ?, ?);"
)) {
statement.setString(1, playerInfo.getUuid().toString());
statement.setString(2, playerInfo.getName());
statement.setString(3, playerInfo.getGameServer());
statement.setString(4, playerInfo.getProxyServer());
statement.setBoolean(5, playerInfo.isOnline());
statement.executeUpdate();
}
} catch (SQLException e) {
e.printStackTrace();
}
@@ -50,4 +56,32 @@ public final class BallBungeeCordUtils {
);
});
}
@Nullable
public static DataSource getDataSource(@Nullable Configuration datasourceConfig) {
if (datasourceConfig == null) {
return null;
}
try {
HikariConfig hikariConfig = new HikariConfig();
String driver = datasourceConfig.getString("driver");
hikariConfig.setDriverClassName(driver);
hikariConfig.setJdbcUrl(datasourceConfig.getString("url"));
hikariConfig.setUsername(datasourceConfig.getString("username"));
hikariConfig.setPassword(datasourceConfig.getString("password"));
hikariConfig.setMaximumPoolSize(datasourceConfig.getInt("maximum-pool-size", 3));
hikariConfig.setMinimumIdle(datasourceConfig.getInt("minimum-idle", 1));
long keepAliveTime = datasourceConfig.getLong("keep-alive-time", 0);
if (keepAliveTime > 5000) {
hikariConfig.setKeepaliveTime(keepAliveTime);
}
hikariConfig.setIdleTimeout(datasourceConfig.getLong("idle-timeout", 10 * 60 * 1000));
hikariConfig.setMaxLifetime(datasourceConfig.getLong("max-lifetime", 30 * 60 * 1000));
hikariConfig.setValidationTimeout(datasourceConfig.getLong("validation-timeout", 5000));
hikariConfig.setPoolName("HamsterBall-Pool");
return new HikariDataSource(hikariConfig);
} catch (Exception | Error e) {
return null;
}
}
}

View File

@@ -13,3 +13,38 @@ server-info:
name: "代理端"
host: 0.0.0.0
port: 25577
# 数据库连接池配置
# 如果注释该选项则默认使用 HamsterCore 中的连接池配置
#datasource:
# # 数据库链接驱动地址
# driver: "com.mysql.jdbc.Driver"
# # 数据库链接填写格式:
# # jdbc:mysql://{数据库地址}:{数据库端口}/{使用的库名}?参数
# # 除非你知道自己在做什么,否则不建议随意更改参数
# url: "jdbc:mysql://sql.hamster3.cn:3306/Test1?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8&autoReconnect=true&useSSL=false&allowPublicKeyRetrieval=true"
# # 用户名
# username: "Test"
# # 密码
# password: "Test123.."
# # 最小闲置链接数
# # 推荐值1~3
# minimum-idle: 0
# # 最大链接数
# # 推荐值不低于3
# maximum-pool-size: 3
# # 保持连接池可用的间隔
# # 除非你的服务器数据库连接经常断开,否则不建议启用该选项
# # 单位:毫秒
# # 默认值为0禁用
# keep-alive-time: 0
# # 连接闲置回收时间
# # 单位:毫秒
# # 推荐值60000010分钟
# idle-timeout: 600000
# # 链接最长存活时间
# # 单位:毫秒
# max-lifetime: 1800000
# # 验证连接存活的超时时间
# # 单位:毫秒
# validation-timeout: 5000

View File

@@ -15,7 +15,6 @@ import cn.hamster3.mc.plugin.ball.common.event.server.ServerOnlineEvent;
import cn.hamster3.mc.plugin.ball.common.listener.BallListener;
import cn.hamster3.mc.plugin.ball.common.listener.ListenerPriority;
import cn.hamster3.mc.plugin.ball.common.utils.OS;
import cn.hamster3.mc.plugin.core.common.api.CoreAPI;
import cn.hamster3.mc.plugin.core.common.data.DisplayMessage;
import cn.hamster3.mc.plugin.core.common.util.CoreUtils;
import cn.hamster3.mc.plugin.core.lib.net.kyori.adventure.text.Component;
@@ -29,6 +28,7 @@ import io.netty.channel.EventLoopGroup;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.sql.DataSource;
import java.sql.*;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
@@ -183,7 +183,7 @@ public abstract class BallAPI {
connect();
try (Connection connection = CoreAPI.getInstance().getConnection()) {
try (Connection connection = BallAPI.getInstance().getDatasource().getConnection()) {
try (Statement statement = connection.createStatement()) {
statement.execute("CREATE TABLE IF NOT EXISTS `hamster_ball_player_info`(" +
"`uuid` CHAR(36) PRIMARY KEY," +
@@ -310,7 +310,7 @@ public abstract class BallAPI {
sendBallMessage(new BallMessageInfo(BALL_CHANNEL, ServerOfflineEvent.ACTION, new ServerOfflineEvent(getLocalServerId())), true);
try (Connection connection = CoreAPI.getInstance().getConnection()) {
try (Connection connection = BallAPI.getInstance().getDatasource().getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(
"DELETE FROM `hamster_ball_server_info` WHERE `id`=?;"
)) {
@@ -460,12 +460,14 @@ public abstract class BallAPI {
if (!cache) {
return;
}
try (Connection connection = CoreAPI.getInstance().getConnection()) {
PreparedStatement statement = connection.prepareStatement("INSERT INTO `hamster_ball_cached_message` VALUES(?, ?);");
statement.setString(1, receiver.toString());
statement.setString(2, message.toJson().toString());
statement.executeUpdate();
statement.close();
try (Connection connection = BallAPI.getInstance().getDatasource().getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(
"INSERT INTO `hamster_ball_cached_message` VALUES(?, ?);"
)) {
statement.setString(1, receiver.toString());
statement.setString(2, message.toJson().toString());
statement.executeUpdate();
}
} catch (Exception e) {
e.printStackTrace();
}
@@ -497,12 +499,14 @@ public abstract class BallAPI {
if (info != null && info.isOnline()) {
continue;
}
try (Connection connection = CoreAPI.getInstance().getConnection()) {
PreparedStatement statement = connection.prepareStatement("INSERT INTO `hamster_ball_cached_message` VALUES(?, ?);");
statement.setString(1, receiver.toString());
statement.setString(2, message.toJson().toString());
statement.executeUpdate();
statement.close();
try (Connection connection = BallAPI.getInstance().getDatasource().getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(
"INSERT INTO `hamster_ball_cached_message` VALUES(?, ?);"
)) {
statement.setString(1, receiver.toString());
statement.setString(2, message.toJson().toString());
statement.executeUpdate();
}
} catch (Exception e) {
e.printStackTrace();
}
@@ -677,25 +681,30 @@ public abstract class BallAPI {
@NotNull
public List<DisplayMessage> getCachedPlayerMessage(@NotNull UUID uuid) throws SQLException {
ArrayList<DisplayMessage> list = new ArrayList<>();
try (Connection connection = CoreAPI.getInstance().getConnection()) {
PreparedStatement statement = connection.prepareStatement("SELECT message FROM `hamster_ball_cached_message` WHERE `uuid`=?;");
statement.setString(1, uuid.toString());
ResultSet set = statement.executeQuery();
while (set.next()) {
DisplayMessage msg = CoreUtils.GSON.fromJson(set.getString("message"), DisplayMessage.class);
list.add(msg);
try (Connection connection = BallAPI.getInstance().getDatasource().getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(
"SELECT message FROM `hamster_ball_cached_message` WHERE `uuid`=?;"
)) {
statement.setString(1, uuid.toString());
try (ResultSet set = statement.executeQuery()) {
while (set.next()) {
DisplayMessage msg = CoreUtils.GSON.fromJson(set.getString("message"), DisplayMessage.class);
list.add(msg);
}
}
}
statement.close();
}
return list;
}
public void removeCachedPlayerMessage(@NotNull UUID uuid) throws SQLException {
try (Connection connection = CoreAPI.getInstance().getConnection()) {
PreparedStatement statement = connection.prepareStatement("DELETE FROM `hamster_ball_cached_message` WHERE `uuid`=?;");
statement.setString(1, uuid.toString());
statement.executeUpdate();
statement.close();
try (Connection connection = BallAPI.getInstance().getDatasource().getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(
"DELETE FROM `hamster_ball_cached_message` WHERE `uuid`=?;"
)) {
statement.setString(1, uuid.toString());
statement.executeUpdate();
}
}
}
@@ -861,4 +870,7 @@ public abstract class BallAPI {
@NotNull
public abstract Logger getLogger();
@NotNull
public abstract DataSource getDatasource();
}

View File

@@ -30,7 +30,6 @@ test {
useJUnitPlatform()
}
tasks.compileJava.dependsOn(":ball-common:build")
tasks.register("shadowJar", Jar) {
dependsOn("jar")
manifest.attributes('Main-Class': 'cn.hamster3.mc.plugin.ball.server.Bootstrap')
@@ -49,6 +48,14 @@ tasks.register("shadowJar", Jar) {
it.isDirectory() ? it : zipTree(it)
}
])
destinationDir(rootProject.buildDir)
destinationDirectory = rootProject.buildDir
}
tasks.build.dependsOn(shadowJar)
tasks {
compileJava {
dependsOn(":ball-common:build")
}
build {
dependsOn(shadowJar)
}
}

View File

@@ -39,13 +39,14 @@ subprojects {
withSourcesJar()
}
tasks.withType(JavaCompile).configureEach {
options.setEncoding("UTF-8")
}
tasks.withType(Jar).configureEach {
from([rootProject.file("LICENSE")])
duplicatesStrategy(DuplicatesStrategy.EXCLUDE)
tasks {
withType(JavaCompile).configureEach {
options.setEncoding("UTF-8")
}
withType(Jar).configureEach {
from([rootProject.file("LICENSE")])
duplicatesStrategy(DuplicatesStrategy.EXCLUDE)
}
}
javadoc {

View File

@@ -1,5 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.4-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-8.2-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists