DarkMatter in Cyberspace
  • Home
  • Categories
  • Tags
  • Archives

Run Vertx App Programmatically


The following codes demonstrate how to start verticles from a plain groovy script (App.groovy), and how to use other groovy class (MyAdd) in a verticle (MyVer & MyVer2):

take vg-server
gradle init --type groovy-application
cat << EOF > build.gradle
plugins {
  id 'groovy'
  id 'application'
  id 'com.github.johnrengelman.shadow' version '1.2.3'
}
repositories {
    jcenter()
}
version = '3.4.2'
sourceCompatibility = '1.8'
mainClassName = 'App'
dependencies {
    compile "io.vertx:vertx-core:$version"
    compile "io.vertx:vertx-lang-groovy:$version"
    testCompile 'org.spockframework:spock-core:1.0-groovy-2.4'
}
EOF
cat << EOF > src/main/groovy/App.groovy
import io.vertx.core.Vertx;
println("hello groovy")
Vertx.vertx().deployVerticle("MyVer")
Vertx.vertx().deployVerticle("MyVer2")
EOF
cat << EOF > src/main/groovy/MyVer.groovy
import io.vertx.core.AbstractVerticle
import MyAdd
public class MyVer extends AbstractVerticle {
  public void start() {
    println("Starting")
    def myadd = new MyAdd()
    println(myadd.add(3, 7))
  }

  public void stop() {
    println("Stopping")
  }
}
EOF
cat << EOF > src/main/groovy/MyVer2.groovy
import io.vertx.core.AbstractVerticle
import MyAdd

public class MyVer2 extends AbstractVerticle {
  public void start() {
    println("Starting")
    def myadd = new MyAdd()
    println(myadd.add(8, 5))
  }

  public void stop() {
    println("Stopping")
  }
}
EOF
cat << EOF > src/main/groovy/MyAdd.groovy
class MyAdd {
  int add(int x, int y) {
    x * 10 + y
  }
}
EOF
gradle run

For the imported groovy class (MyAdd), its filename (MyAdd.groovy) must be the same with its class name. The file must be placed in the folder as the package named refers. For example, after add package com.biot into MyAdd.groovy, the file must be placed into "src/main/groovy/com/biot". Or the importing verticle (MyVer.groovy) can not use class "MyAdd" with import com.biot.MyAdd.



Published

Sep 18, 2017

Last Updated

Sep 18, 2017

Category

Tech

Tags

  • gradle 11
  • groovy 13
  • vertx 5

Contact

  • Powered by Pelican. Theme: Elegant by Talha Mansoor