代码之家  ›  专栏  ›  技术社区  ›  Hasan A Yousef Michael Benjamin

如何创建。Ktor嵌入式服务器的jar(创建可执行文件)

  •  9
  • Hasan A Yousef Michael Benjamin  · 技术社区  · 7 年前

    我对科特林、克托尔和格雷德尔很陌生。能够按照Ktor站点中的说明创建嵌入式服务器,代码如下:

    博客应用程序。千吨 :

    package blog
    
    import org.jetbrains.ktor.netty.*
    import org.jetbrains.ktor.routing.*
    import org.jetbrains.ktor.application.*
    import org.jetbrains.ktor.features.*
    import org.jetbrains.ktor.host.*
    import org.jetbrains.ktor.http.*
    import org.jetbrains.ktor.response.*
    
    fun Application.module() {
        install(DefaultHeaders)
        install(CallLogging)
        install(Routing) {
            get("/") {
                call.respondText("My Example Blog  sfs 122", ContentType.Text.Html)
            }
        }
    }
    
    fun main(args: Array<String>) {
        embeddedServer(Netty, 8080, watchPaths = listOf("BlogAppKt"), module = Application::module).start()
    }
    

    建筑格拉德尔

    group 'Example'
    version '1.0-SNAPSHOT'
    
    buildscript {
        ext.kotlin_version = '1.1.4-3'
    
        repositories {
            mavenCentral()
        }
        dependencies {
            classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        }
    }
    
    apply plugin: 'java'
    apply plugin: 'kotlin'
    
    sourceCompatibility = 1.8
    ext.ktor_version = '0.4.0'
    
    repositories {
        mavenCentral()
        maven { url  "http://dl.bintray.com/kotlin/ktor" }
        maven { url "https://dl.bintray.com/kotlin/kotlinx" }
    }
    
    dependencies {
        compile "org.jetbrains.kotlin:kotlin-stdlib-jre8:$kotlin_version"
        compile "org.jetbrains.ktor:ktor-core:$ktor_version"
        compile "org.jetbrains.ktor:ktor-netty:$ktor_version"
        compile "ch.qos.logback:logback-classic:1.2.1"
        testCompile group: 'junit', name: 'junit', version: '4.12'
    }
    
    compileKotlin {
        kotlinOptions.jvmTarget = "1.8"
    }
    compileTestKotlin {
        kotlinOptions.jvmTarget = "1.8"
    }
    kotlin {
        experimental {
            coroutines "enable"
        }
    }
    

    服务器在以下位置运行正常: localhost:8080

    我可以在 out

    C:\Users\Home\IdeaProjects\Example\out\production\classes\blog

    enter image description here

    1 回复  |  直到 7 年前
        1
  •  10
  •   Hasan A Yousef Michael Benjamin    7 年前

    build.gradle 文件:

    jar {
        baseName '<jar_name>'
        manifest {
            attributes 'Main-Class': 'blog.BlogAppKt'
        }
    
        from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } }
    }
    

    gradle clean jar build/libs 然后运行 java -jar <jar_name>.jar .

    javaw -jar <jar_name>.jar 而不是java(如果java\u HOME定义不好,您可能需要确保它在路径上)。这将在没有任何控制台的情况下运行它。

    P、 你也可以使用 application 插件或 shadowJar .