[vert.x] Vert.x core examples - 4. Verticle examples

2016. 3. 25. 12:00Java/Vert.x

Verticle examples

이 예제는 verticles을 배포하고 해제하는 것을 보여 드린답니다.

Deploy example

이 예제는 아래를 포함한 여러 방법으로 추가 verticle를 배포하는 verticle을 보여줍니다.

- 배포하기 위해 대기 없이 배포하는 것 
- 배포하고 배포하기 위해 대기하는 것
- 배포하는 동안 다른 verticle에 config 전달하는 것 
- 하나 혹은 그 이상의 인스턴스를 배포하는 것
- worker verticle 로써 배포하는 것
-verticle 배포를 명확하게 해제하는 것



public class OtherVerticle extends AbstractVerticle {

    /**
     * If your verticle does a simple, synchronous start-up then override this method and put your start-up
     * code in there.
     *
     * @throws Exception
     */
    @Override
    public void start() throws Exception {
        //The start method will be called when the verticle is deployed
        System.out.println("In OtherVerticle.start");

        System.out.println("Config is " + config());
    }

    /**
     * If your verticle has simple synchronous clean-up tasks to complete then override this method and put your clean-up
     * code in there.
     *
     * @throws Exception
     */
    @Override
    public void stop() throws Exception {
        // You can optionally override the stop method too, if you have some clean-up to do
        System.out.println("In OtherVerticle.stop");
    }
}






@Override
public void start() throws Exception {
    System.out.println("Main verticle has started, let's deploy some others...");

    //Different ways of deploying verticles

    //Deploy a verticle and don't wait for it to start
    vertx.deployVerticle("io.vertx.example.core.verticle.deploy.OtherVerticle");

    //Deploy another instance and want for it to start
    vertx.deployVerticle("io.vertx.example.core.verticle.deploy.OtherVerticle",res->{
        if(res.succeeded()){
            String deploymentID = res.result();

            System.out.println("Other verticle deployed ok, deploymentID = " + deploymentID);

            //You can also explicitly undeploy a verticle deployment
            //Note that this is usually unnecessary as any verticles deployed by a verticle will be automatically
            //undeployed when the parent verticle is unployed

            vertx.undeploy(deploymentIDres2->{
                if(res2.succeeded()){
                    System.out.println("Undeployed ok!");
                }else{
                    res2.cause().printStackTrace();
                }
            });
        }
    });

    //Deploy specifying some config
    JsonObject config = new JsonObject().put("foo","bar");
    vertx.deployVerticle("io.vertx.example.core.verticle.deploy.OtherVerticle", new DeploymentOptions().setConfig(config));

    //Deploy 10 instances
    vertx.deployVerticle("io.vertx.example.core.verticle.deploy.OtherVerticle",new DeploymentOptions().setInstances(10));

    //Deploy it as a worker verticle
    vertx.deployVerticle("io.vertx.example.core.verticle.deploy.OtherVerticle",new DeploymentOptions().setWorker(true));
}


실행 결과는


Main verticle has started, let's deploy some others...
In OtherVerticle.start
In OtherVerticle.start
In OtherVerticle.start
In OtherVerticle.start
In OtherVerticle.start
In OtherVerticle.start
In OtherVerticle.start
In OtherVerticle.start
In OtherVerticle.start
Config is {}
Config is {"foo":"bar"}
In OtherVerticle.start
Config is {}
Config is {}
Config is {}
In OtherVerticle.start
Config is {}
Config is {}
Config is {}
In OtherVerticle.start
Config is {}
In OtherVerticle.start
Other verticle deployed ok, deploymentID = 890e1113-c511-41bc-8450-f234c9c4d0b1
Config is {}
Config is {}
Config is {}
Config is {}
In OtherVerticle.start
Config is {}
In OtherVerticle.stop
Undeployed ok!



Asynchronous deployment example

위의 배포 예제와 비슷합니다만, 이것은 비동기로 될수 있는 Verticle의 시작과 종료를 하는 방법을 보여드립니다.
이것은 verticle이 약간의 시간이 필요로한 것을 하기 위한 startup 또는 cleanup 가지고 있을때 유용하고,
우리는 이벤트 루프가 블락되는 것을 피하기를 원한답니다.



@Override
public void start() throws Exception {
    System.out.println("Main verticle has started, let's deploy some others...");

    //Deploy another instance and want for it to start
    vertx.deployVerticle("io.vertx.example.core.verticle.asyncstart.OtherVerticle"res->{
        if(res.succeeded()){
            String deploymentID = res.result();

            System.out.println("Other verticle deployed ok, deploymentId = " + deploymentID);

            vertx.undeploy(deploymentIDres2->{
                if(res2.succeeded()){
                    System.out.println("Undeployed ok!");
                }else{
                    res2.cause().printStackTrace();
                }
            });
        }
    });
}




public class OtherVerticle extends AbstractVerticle{
    /**
     * Start the verticle.<p>
     * This is called by Vert.x when the verticle instance is deployed. Don't call it yourself.<p>
     * If your verticle does things in it's startup which take some time then you can override this method
     * and call the startFuture some time later when start up is complete.
     *
     * @param startFuture a future which should be called when verticle start-up is complete.
     * @throws Exception
     */
    @Override
    public void start(Future<Void> startFuture) throws Exception {
        System.out.println("In OtherVerticle.start (async)");

        //This veticle takes some time to start (maybe it has to deploy other verticles or whatever)
        //So we override the async version of start(), then we can mark the verticle as started some time later
        //when all the show startup is done, without blocking the actual start method.

        //we simulate this long startup time by setting a timer
        vertx.setTimer(2000tid ->{
            //Now everything is started, we can tell Vert.x this verticle is started when it will call the deploy handler
            // of the caller that originally deployed it.

            System.out.println("Startup tasks are now complete, OtherVerticle is now started");

            startFuture.complete();
        });

    }

    /**
     * Stop the verticle.<p>
     * This is called by Vert.x when the verticle instance is un-deployed. Don't call it yourself.<p>
     * If your verticle does things in it's shut-down which take some time then you can override this method
     * and call the stopFuture some time later when clean-up is complete.
     *
     * @param stopFuture a future which should be called when verticle clean-up is complete.
     * @throws Exception
     */
    @Override
    public void stop(Future<Void> stopFuture) throws Exception {
       //If you have slow cleanup tasks to perform, you can similarly override the async stop method

        vertx.setTimer(2000tid->{
            System.out.println("Cleanup tasks are now complete, OtherVerticle is now stopped!");

            stopFuture.complete();
        });
    }
}

시간이 걸리는 작업을 하는 Verticle 을 이렇게 비동기 처리하면 이벤트 루프에 행이 걸리는 것을 방지 하겠다 라는 뜻인듯...

실행 결과는 

Main verticle has started, let's deploy some others...
In OtherVerticle.start (async)
Startup tasks are now complete, OtherVerticle is now started
Other verticle deployed ok, deploymentId = 9b89ccba-0806-4c70-891f-6483770a25ad
Cleanup tasks are now complete, OtherVerticle is now stopped!
Undeployed ok!


Worker Verticle example

Worker verticle을 어떻게 생성할수 있고, thead가 그것들사이에 상호작용(interacting) 할 때 스위칭을 하는 것을 설명하는 예제입니다.
worker verticle은 이벤트 루프상에서 실행되지 않기에, 블록킹 동작들을 할수 있습니다.



@Override
public void start() throws Exception {
    System.out.println("[Main] Running in " + Thread.currentThread().getName());
    vertx
            .deployVerticle("io.vertx.example.core.verticle.worker.WorkerVerticle",
                    new DeploymentOptions().setWorker(true));

    vertx.eventBus().send(
            "sample.data",
            "hello vert.x",
            r -> {
                System.out.println("[Main] Receiving reply ' " + r.result().body()
                        + "' in " + Thread.currentThread().getName());
            }
    );
}



@Override
public void start() throws Exception {
    System.out.println("[worker] Starting in " + Thread.currentThread().getName());

    vertx.eventBus().consumer("sample.data"message->{
        System.out.println("[Worker] Consuming data in " + Thread.currentThread().getName());
        String body = (String) message.body();
        message.reply(body.toUpperCase());
    });
}

실행 결과는 

[Main] Running in vert.x-eventloop-thread-1
[worker] Starting in vert.x-worker-thread-0
[Worker] Consuming data in vert.x-worker-thread-1
[Main] Receiving reply ' HELLO VERT.X' in vert.x-eventloop-thread-1