[vert.x] Vert.x core examples - 5. Execute blocking & high Availability examples

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

Execute blocking  examples


이 예제는 어떻게 여러분이 이벤트 루프를 block 하지 않는 방법으로 여러분의 non blocking code와 함께 안에 blocking code를 포함할 수 있는지를 설명합니다.



@Override
public void start() throws Exception {
    vertx.createHttpServer().requestHandler(request->{
        // Let's say we have to call a blocking API (e.g. JDBC) to execute a query for each request.
        // We can't do this directly or it will block the event loop
        // But you can do this using executeBlocking :

        vertx.<String>executeBlocking(future->{
            // Do the blocking operation in here
            //Imagine this was a call to a blocking API to get the result

            try{
                Thread.sleep(5000);
            }catch (Exception ignore){
            }
            String result = "armadillos!";
            future.complete(result);
        },res->{
            if(res.succeeded()){
                request.response().putHeader("content-type","text/plain").end(res.result());
            }else{
                res.cause().printStackTrace();
            }
        });
    }).listen(8080);
}

확인은 localhost:8080 으로 웹 브라우저를 통해서 확인 가능합니다. 

High Availability

이 예제는 vert.x 의 고가용성 기능에 대해서 설명합니다.
가능할때, 오리지널 node가 갑작스레(abruptly) 죽었을때, vert.x는 다른 노드에 verticles를 재배포합니다. 
==> 404 가 떴습니다... 소스가 이동했네요



public class Server extends AbstractVerticle {

// Convenience method so you can run it in your IDE
public static void main(String[] args) {
Launcher.main(new String[] { "run", Server.class.getName(), "-ha"});
}

@Override
public void start() throws Exception {
vertx.createHttpServer().requestHandler(req -> {
final String name = ManagementFactory.getRuntimeMXBean().getName();
req.response().end("Happily served by " + name);
}).listen(8080);
}
}



public class BareInstance {
    // Just start a bare instance of vert.x .
    // It will receive the Server verticle when the process is killed.
    public static void main(String[] args) {
        Launcher.main(new String[]{"bare"});
    }
}

이 예제를 진행하기 위해서는, 여러분은 cluster가 작동하도록 할 필요가 있답니다.
Hazelcast를 구성하고, cluster-host가 필요로로 한 것을 필요하면 컴앤드에 추가하세요.

IDE 에서
 - Server class의 main 메소드를 실행 하시고
 - http://localhost:8080 에 접속해서 체크
 - bareInstance 클래스의 메인 메소드를 실행해서 bare 인스턴스를 시작하세요.

터미널에서 ,  Server 클래스에 연관된 프로세스를 찾아서, kill -9 죽여주시길 바랍니다.
verticle은 bare 인스턴스에 의해서 배포디ㅗ어 질 것입니다.
만약 페이지를 새로 고치게 되면, 메세지는 조금 다르게 보여져야 합니다.

Command line 에서는
세개의 터미널이 필요합니다. HA 를 보여주기 위해서는 말이죠
첫번째 프로젝트 컴파일은 mvn clean package 하시고
첫번째 터미널에서, _core-example' 디렉토리에 가서 런칭 합니다.

vertx run io.verx.example.core.ha.Server -ha -cp target/classes

http://localhost:8080에 접속해서 보면 아래와 같은 것을 보겠죠

Happily served by 23243@Macintosh.local

보여진 아이디는 OS 와 JVM 명세 입니다 그래서 여러분은 전혀 다른 것을 보게 되겠죠.
두번째 터미널에서는 _core-example 디렉토리에 가서 런칭 합니다.

vertx bare -cp target/classes/

세번째 터미널에서는, java process 를 보고 킬을 해버립니다.

>jps | grep Launcher
23243 Launcher
23242 Launcher
> kill -9 23243

그다음 브라우저에서 다시 확인 하면 아마도 다른 아이디가 보이게 됩니다.

verticle이 마이그레이션 되었답니다.

JavaScript Verticle and NPM

Verticles은 CommonJS module format 또는 NPM module format을 사용할 수 있는 JavaScript에서 실행했습니다. 

NPM module module format : https://www.npmjs.com/

그것들은 또한 NPM 와 CommonJS modules이 필요할수 있습니다.
이 예제는 어떻게 verticle이 NPM module format를 사용할수 있는지, 이 포멧을 사용한 verticle들을 배포하고 , 다른 NPMs을 요구하는지에 대해서 보여줍니다.

NPMs은 NODE_PATH 환경변수에 의해 가르키는 디렉토리로 부터 해결되어 집니다.
이 이유를 위해, 우리는 NODE_PATH를 현제 디렉토리에 세팅합니다. verticle를 런칭하기 전에 말이죠.

cd src/main/js/npm
export NODE_PATH=$PWD
vertx run my_npm_verticle.js



Groovy verticles

Vert.x은 Groovy에서 verticle을 개발하기 위한 몇가지 포멧들을 지원합니다. 

이 directory는 다른 포멧들을 설명합니다.

- plain script - 일반 Groovy script로 개발된 verticle
- plain script with hooks - veticle이 배치되어지고, 내려질때 , vert.x에 의해서 호출되어진 hooks를 갖는 스크립트로 개발된 Verticle.
- class extending AbstarctVerticle - AbstractVerticle을 확장한 클래스로 개발된 verticle
- class extending GroovyVerticle - GroovyVerticle을 확장한 클래스로 개발된 verticle

여러분은 이 예제들을 vertx 명령 라인을 사용해서 가동할수 있습니다.
예를 들면,

vertx run script.groovy