johnclot69 пре 6 дана
родитељ
комит
531db00ec1

+ 27 - 21
build.gradle

@@ -1,58 +1,64 @@
 subprojects {
-    apply plugin: 'java';
-    apply plugin: 'idea';
+    apply plugin: "java";
+    apply plugin: "idea";
 
     repositories {
         // 优先使用本地 Maven 缓存
         mavenLocal()
+        // 官方仓库
+        mavenCentral()
         // 阿里云公共仓库
-        maven { url = 'https://maven.aliyun.com/repository/public' }
+        maven { url = "https://maven.aliyun.com/repository/public" }
         // 阿里云 Gradle 插件仓库
-        maven { url = 'https://maven.aliyun.com/repository/gradle-plugin' }
-        // 官方仓库作为备用
-        mavenCentral()
+        maven { url = "https://maven.aliyun.com/repository/gradle-plugin" }
     }
 
     // 配置Java版本
-    JavaLanguageVersion.of(23)
+    java {
+        toolchain {
+            languageVersion = JavaLanguageVersion.of(javaVersion.toInteger())
+        }
+    }
 
     // 配置编译选项
     tasks.withType(JavaCompile).configureEach {
-        options.encoding = 'UTF-8'
+        options.encoding = "UTF-8"
         options.incremental = true // 启用增量编译
 
         // 启用现代编译参数
         options.compilerArgs.addAll([
-//                '--enable-preview',          // 启用预览特性
-                '-parameters'                // 保留方法参数名
+                // 启用预览特性
+//                "--enable-preview",
+                // 保留方法参数名
+                "-parameters"
         ])
     }
 
     // 现代任务注册方式
-    tasks.register('copyAllDependencies', Copy) {
-        group = 'Build'
-        description = 'Copies all dependencies to lib directory'
+    tasks.register("copyAllDependencies", Copy) {
+        group = "Build"
+        description = "Copies all dependencies to build/libs/lib directory"
 
-        from configurations.runtimeClasspath
-        into layout.buildDirectory.dir("libs/lib")  // 使用现代路径 API
+        from(configurations.runtimeClasspath)
+        into(layout.buildDirectory.dir("libs/lib").get().asFile)
 
         // 添加分类器过滤(可选)
-        include '*.jar'
-        exclude '*-sources.jar', '*-javadoc.jar'
+        include('*.jar')
+        exclude('*-sources.jar', '*-javadoc.jar')
     }
 
     // 构建后自动复制依赖(按需启用)
-    tasks.named('build') {
-        finalizedBy tasks.named('copyAllDependencies')
+    tasks.named('build').configure {
+        finalizedBy(tasks.named('copyAllDependencies'))
     }
 
-    // 测试配置现代化
+    // 测试配置
     tasks.named('test', Test) {
         useJUnitPlatform()
         maxHeapSize = '2G'
 
         // 并行测试配置
-        maxParallelForks = Runtime.runtime.availableProcessors().intdiv(2) ?: 1
+        maxParallelForks = (Runtime.runtime.availableProcessors() / 2).toInteger() ?: 1
         forkEvery = 100
     }
 }

+ 54 - 0
gradle.properties

@@ -0,0 +1,54 @@
+# -------- 编译环境配置 --------
+
+# 启用 Gradle 守护进程,加快后续构建速度
+org.gradle.daemon=true
+
+# 启用并行构建(适用于多模块项目)
+org.gradle.parallel=true
+
+# 开启配置缓存(Gradle 7+ 推荐)
+#org.gradle.configuration-cache=true
+
+# 开启构建缓存
+org.gradle.caching=true
+
+# 最大工作线程数(根据实际 CPU 内核数调整,如 8 核建议设置为 6~8)
+org.gradle.workers.max=8
+
+# JVM 参数(适配 JDK 23 和 ZGC)
+org.gradle.jvmargs=\
+ -XX:+UseZGC \
+ -XX:+ZGenerational \
+ -XX:MaxRAMPercentage=70 \
+ -XX:-ZUncommit \
+ -XX:+AlwaysPreTouch \
+ -XX:+HeapDumpOnOutOfMemoryError \
+ -XX:HeapDumpPath=heapdump.hprof \
+ -Dfile.encoding=UTF-8 \
+ -Djava.security.egd=file:/dev/./urandom \
+ -Dnetworkaddress.cache.ttl=10 \
+ -Dsun.net.client.defaultConnectTimeout=60000 \
+ -Dsun.net.client.defaultReadTimeout=60000 \
+ -Djava.awt.headless=true \
+ -Dio.netty.tryReflectionSetAccessible=true
+
+# -------- 项目版本/变量配置(可供 build.gradle 引用) --------
+
+# Java 版本(供 build.gradle 使用,如 JavaPluginExtension.toolchain.languageVersion.set(JavaLanguageVersion.of(javaVersion)))
+javaVersion=23
+
+# 公司或组织通用 groupId
+group=com.example
+
+# 默认版本号(可用于所有模块)
+version=1.0.0-SNAPSHOT
+
+# Maven 发布配置(如使用 Maven 发布插件)
+# mavenRepoRelease=https://your-nexus/releases/
+# mavenRepoSnapshot=https://your-nexus/snapshots/
+
+# -------- 代理配置(如使用公司代理构建) --------
+# systemProp.http.proxyHost=proxy.example.com
+# systemProp.http.proxyPort=8080
+# systemProp.https.proxyHost=proxy.example.com
+# systemProp.https.proxyPort=8080

+ 3 - 3
gradle/wrapper/gradle-wrapper.properties

@@ -1,7 +1,7 @@
 distributionBase=GRADLE_USER_HOME
 distributionPath=wrapper/dists
-distributionUrl=https\://services.gradle.org/distributions/gradle-8.14-bin.zip
-networkTimeout=10000
-validateDistributionUrl=true
 zipStoreBase=GRADLE_USER_HOME
 zipStorePath=wrapper/dists
+distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.2-all.zip
+networkTimeout=10000
+validateDistributionUrl=true

+ 34 - 30
incubator-app/build.gradle

@@ -1,46 +1,50 @@
 plugins {
-    id 'java'
-    id 'application'
-    id 'com.github.johnrengelman.shadow' version "8.1.1"
+    id("java")
+    id("application")
+    id("com.github.johnrengelman.shadow") version "8.1.1"
 }
 
-group = 'com.incubator.app'
-version = '1.0-SNAPSHOT'
+group = "com.incubator.app"
 
 // 项目依赖
 dependencies {
     // 子模块依赖
-    implementation project(':incubator-game')
+    implementation project(":incubator-game")
 
     // 测试依赖
-    testImplementation platform("org.junit:junit-bom:5.10.0")
-    testImplementation "org.junit.jupiter:junit-jupiter-api"
-    testRuntimeOnly "org.junit.jupiter:junit-jupiter-engine"
+    testImplementation("org.junit.jupiter:junit-jupiter-api:5.10.2")
+    testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:5.10.2")
 }
 
 // 使用 Gradle 的现代 API 定义源集
 sourceSets {
-    main {
+    conf {
         resources {
-            srcDirs = ['conf'] // 移除 += 以明确覆盖默认值
+            srcDirs("conf")
         }
     }
 }
 
 application {
     // 类型安全的主类配置
-    mainClass = "App"
+    mainClass = "com.incubator.app.App"
 
     // 配置 JVM 参数,支持高并发和性能优化
     applicationDefaultJvmArgs = [
-            "-XX:+UseZGC",                   // 使用 ZGC 垃圾回收器,适合高并发
-            "-Xmx2G",                       // 限制最大堆大小
-            "-XX:+UnlockExperimentalVMOptions", // 启用实验性选项
-            "-XX:ZUncommitDelay=300",       // 减少内存未使用时的延迟
-            "-XX:+HeapDumpOnOutOfMemoryError", // OOM 时生成堆转储
-            "-XX:ZCollectionInterval=3",
-            "-Dio.netty.allocator.numDirectArenas=0", // 禁用堆外内存
-            "-Dio.netty.leakDetection.level=PARANOID"
+            "-XX:+UseZGC",                         // 启用 ZGC 垃圾回收器,低延迟适合高并发
+            "-XX:+ZGenerational",                  // 开启分代 ZGC 模式,优化GC性能
+            "-XX:MaxRAMPercentage=70",             // JVM 最大内存占用为系统内存的70%
+            "-XX:-ZUncommit",                      // 禁止 JVM 主动归还未使用内存给系统
+            "-XX:+AlwaysPreTouch",                 // JVM 启动时预先分配所有堆内存,加速运行时性能
+            "-XX:+HeapDumpOnOutOfMemoryError",     // 内存溢出时自动生成堆转储文件,用于诊断
+            "-XX:HeapDumpPath=heapdump.hprof",     // 指定堆转储文件的保存路径
+            "-Dfile.encoding=UTF-8",               // 设置文件默认字符编码为 UTF-8
+            "-Djava.security.egd=file:/dev/./urandom", // 使用非阻塞随机数生成器,加快启动
+            "-Dnetworkaddress.cache.ttl=10",       // DNS缓存有效时间设为10秒,避免长时间缓存问题
+            "-Dsun.net.client.defaultConnectTimeout=60000", // 默认网络连接超时时间设为60秒
+            "-Dsun.net.client.defaultReadTimeout=60000",    // 默认网络读取超时时间设为60秒
+            "-Djava.awt.headless=true",            // 启用无头模式,避免图形界面环境相关问题
+            "-Dio.netty.tryReflectionSetAccessible=true" // Netty启用反射访问,以提高Java高版本兼容性与性能
     ]
 }
 
@@ -49,7 +53,7 @@ tasks.withType(JavaCompile).configureEach {
 }
 
 // 禁用默认的 JAR 任务,因为我们使用 Shadow JAR
-tasks.named('jar') {
+tasks.jar {
     enabled = false
 }
 
@@ -57,23 +61,23 @@ tasks.named('jar') {
 tasks.shadowJar {
     zip64 = true
     // 设置 JAR 包的基本名称
-    archiveBaseName = 'incubator-app'
+    archiveBaseName.set("incubator-app")
     // 使用项目的版本号作为 JAR 的版本
-    archiveVersion = project.version
+    archiveVersion.set(project.version.toString())
     // 移除分类器,生成的 JAR 没有后缀
-    archiveClassifier = ''
+    archiveClassifier.set("")
 
     // 添加自定义清单
     manifest {
         // 使用动态设置的主类
-        attributes 'Main-Class': application.mainClass.get()
+        attributes("Main-Class": application.mainClass.get())
     }
 
     // 将 conf 目录包含到最终的 JAR 文件中
-    from('conf') { into('conf') }
+    from("conf") { into("conf") }
 
     // 可选:排除不必要的依赖
-    exclude 'META-INF/*.SF', 'META-INF/*.DSA', 'META-INF/*.RSA'
+    exclude("META-INF/*.SF", "META-INF/*.DSA", "META-INF/*.RSA")
 
     // 避免重复打包无关的文件
     duplicatesStrategy = DuplicatesStrategy.EXCLUDE
@@ -89,8 +93,8 @@ tasks.test {
 }
 
 // 将 Shadow JAR 绑定到 assemble 阶段
-tasks.named('assemble') {
-    dependsOn tasks.named = 'shadowJar' as Task
+tasks.named("assemble") {
+    dependsOn(tasks.named("shadowJar"))
 }
 
 // 增加构建信息任务
@@ -109,6 +113,6 @@ tasks.register("buildInfo") {
 }
 
 // 清理任务优化
-tasks.named('clean') {
+tasks.named("clean", Delete).configure {
     delete(layout.buildDirectory)
 }

+ 19 - 15
incubator-core/build.gradle

@@ -1,33 +1,37 @@
 plugins {
-    id "java-library"
+    id("java-library")
 }
 
 group = "com.incubator.core"
-version = "1.0-SNAPSHOT"
 
 // 项目依赖
 dependencies {
     // 日志相关
-    api "org.slf4j:slf4j-api:2.0.16" // SLF4J API
-    api "org.apache.logging.log4j:log4j-slf4j2-impl:2.24.2" // SLF4J -> Log4j2 桥接
-    api "org.apache.logging.log4j:log4j-core:2.24.2" // Log4j2 实现
+    api("org.slf4j:slf4j-api:2.0.16") // SLF4J API
+    api("org.apache.logging.log4j:log4j-slf4j2-impl:2.24.2") // SLF4J -> Log4j2 桥接
+    api("org.apache.logging.log4j:log4j-core:2.24.2") // Log4j2 实现
 
     // 系统核心依赖
-    api "net.onedaybeard.artemis:artemis-odb:2.3.0"
-    api "com.lmax:disruptor:4.0.0" // 高性能队列
+    api("net.onedaybeard.artemis:artemis-odb:2.3.0")
+    api("com.lmax:disruptor:4.0.0") // 高性能队列
 
     // 网络通信和序列化
-    api "io.netty:netty-all:4.2.1.Final" // Netty 全功能包
-    api "org.msgpack:msgpack-core:0.9.9" // MessagePack 序列化
+    api("io.netty:netty-all:4.2.1.Final") // Netty 全功能包
+    api("org.msgpack:msgpack-core:0.9.9") // MessagePack 序列化
 
     // 测试依赖
-    testImplementation platform("org.junit:junit-bom:5.10.0")
-    testImplementation "org.junit.jupiter:junit-jupiter-api"
-    testRuntimeOnly "org.junit.jupiter:junit-jupiter-engine"
+    testImplementation("org.junit.jupiter:junit-jupiter-api:5.10.2")
+    testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:5.10.2")
 }
 
-configurations.configureEach {
-    exclude group: "ch.qos.logback", module: "logback-classic"
+// 清理冗余的 copyAllDependencies 任务,如有必要重新定义
+tasks.build {
+    dependsOn(tasks.jar)
 }
 
-build.dependsOn(copyAllDependencies)
+tasks.test {
+    useJUnitPlatform()
+    testLogging {
+        events("PASSED", "FAILED", "SKIPPED")
+    }
+}

+ 11 - 9
incubator-core/src/main/java/com/incubator/core/network/NettySystem.java

@@ -32,13 +32,15 @@ import java.util.concurrent.ThreadFactory;
 public class NettySystem extends BaseSystem {
 
     private final int port;
-//    private static final int BOSS_THREADS = 1;
-    private static final int BOSS_THREADS = Math.max(1, Runtime.getRuntime().availableProcessors() / 2);
+    private static final int BOSS_THREADS = 1;
+//    private static final int BOSS_THREADS = Math.max(1, Runtime.getRuntime().availableProcessors() / 2);
     private static final int WORKER_THREADS = Math.max(1, Runtime.getRuntime().availableProcessors() * 2);
 
     private final ServerBootstrap bootstrap = new ServerBootstrap();
     private IoEventLoopGroup bossGroup;
     private IoEventLoopGroup workerGroup;
+
+    private final String name = "NettyServer";
     private Channel serverChannel;
 
     public NettySystem(int port) {
@@ -60,13 +62,13 @@ public class NettySystem extends BaseSystem {
             this.serverChannel = future.channel();
 
             if (future.isSuccess()) {
-                Logger.info("[Netty] 服务启动成功,绑定端口: {}", address.toString());
+                Logger.info("[{}] 服务启动成功,绑定端口: {}", this.name, address.toString());
             } else {
-                Logger.error("[Netty] 服务启动失败: {}", future.cause());
+                Logger.error("[{}] 服务启动失败: {}", this.name, future.cause());
             }
         } catch (InterruptedException e) {
             Thread.currentThread().interrupt();
-            Logger.error("[Netty] 服务启动异常: {}", e.getMessage(), e);
+            Logger.error("[{}] 服务启动异常: {}", this.name, e.getMessage(), e);
         }
     }
 
@@ -145,9 +147,9 @@ public class NettySystem extends BaseSystem {
             }
             this.shutdownEventLoopGroup(this.bossGroup, "BossGroup");
             this.shutdownEventLoopGroup(this.workerGroup, "WorkerGroup");
-            Logger.info("[Netty] 服务停止成功");
+            Logger.info("[{}] 服务停止成功", this.name);
         } catch (InterruptedException e) {
-            Logger.error("[Netty] 服务停止异常: {}", e.getMessage(), e);
+            Logger.error("[{}] 服务停止异常: {}", this.name, e.getMessage(), e);
         }
     }
 
@@ -155,10 +157,10 @@ public class NettySystem extends BaseSystem {
         if (group != null) {
             try {
                 group.shutdownGracefully().sync();
-                Logger.info("[Netty] {} 已关闭", groupName);
+                Logger.info("[{}] {} 已关闭", this.name, groupName);
             } catch (InterruptedException e) {
                 Thread.currentThread().interrupt();
-                Logger.error("[Netty] {} 关闭失败: {}", groupName, e.getMessage(), e);
+                Logger.error("[{}] {} 关闭失败: {}", this.name, groupName, e.getMessage(), e);
             }
         }
     }

+ 12 - 7
incubator-game/build.gradle

@@ -1,20 +1,25 @@
 plugins {
-    id 'java-library'
+    id("java-library")
 }
 
 group = 'com.incubator.game'
-version = '1.0-SNAPSHOT'
 
 // 项目依赖
 dependencies {
-    testImplementation(platform('org.junit:junit-bom:5.10.0'))
-    testImplementation('org.junit.jupiter:junit-jupiter')
+    api project(path: ':incubator-core')\
 
-    api project(path: ':incubator-core')
+    testImplementation("org.junit.jupiter:junit-jupiter-api:5.10.2")
+    testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:5.10.2")
 }
 
 configurations.configureEach {
-    exclude group: 'ch.qos.logback', module: 'logback-classic'
+    exclude group: "ch.qos.logback", module: "logback-classic"
 }
 
-build.dependsOn(copyAllDependencies)
+// 配置测试任务
+tasks.named("test", Test) {
+    useJUnitPlatform()
+    testLogging {
+        events("PASSED", "FAILED", "SKIPPED")
+    }
+}