vertx微服務集羣
有四種方式
我目前使用了ZK,動物園
下載後進入bin,運行zKServer
創建項目
mkdir hello-microservice-message
cd hello-microservice-message
mvn io.fabric8:vertx-maven-plugin:1.0.5:setup \
-DprojectGroupId=io.vertx.microservice \
-DprojectArtifactId=hello-microservice-message \
-Dverticle=io.vertx.book.message.HelloMicroservice
增加依賴
<dependency>
<groupId>io.vertx</groupId>
<artifactId>vertx-zookeeper</artifactId>
<version>3.5.1</version>
</dependency>
修改HelloMicroservice.java,start改爲
@Override
public void start() {
// Receive message from the address 'hello'
vertx.eventBus().<String>consumer("hello", message -> {
JsonObject json = new JsonObject()
.put("served-by", this.toString());
// Check whether we have received a payload in the
// incoming message
if (message.body().isEmpty()) {
message.reply(json.put("message", "hello"));
} else {
System.out.println(message.body());
message.reply(json.put("message",
"hello3"+ message.body()));
}
});
}
創建另一個項目
mkdir hello-consumer-microservice-message
cd hello-consumer-microservice-message
mvn io.fabric8:vertx-maven-plugin:1.0.5:setup \
-DprojectGroupId=io.vertx.microservice \
-DprojectArtifactId=hello-consumer-microservice-message \
-Dverticle=io.vertx.book.message.HelloConsumerMicroservice \
-Ddependencies=rx
增加依賴
<dependency>
<groupId>io.vertx</groupId>
<artifactId>vertx-zookeeper</artifactId>
<version>3.5.1</version>
</dependency>
HelloConsumerMicroservice.java的start改爲
@Override public void start() { vertx.createHttpServer()
.requestHandler( req -> {
System.out.println(this.toString());
EventBus bus = vertx.eventBus();
Single<JsonObject> obs1 = bus .<JsonObject>rxSend("hello", "Luke")
.map(Message::body);
Single<JsonObject> obs2 = bus
.<JsonObject>rxSend("hello", "Leia") .map(Message::body);
Single
.zip(obs1, obs2, (luke, leia) ->
new JsonObject()
.put("Luke", luke.getString("message")
+ " from "
+ luke.getString("served-by"))
.put("Leia", leia.getString("message")
+ " from "
+ leia.getString("served-by"))
)
.subscribe(
x -> req.response().end(x.encodePrettily()),
t -> {
t.printStackTrace(); req.response().setStatusCode(500) .end(t.getMessage());
}
);
})
.listen(8082);
}
兩個項目都打包
mvn clean package
都以集羣模式運行
java -jar name.jar -ha
這個時候ZK的窗口會看到發現了節點。ZK和vert.x的ZK依賴host和port都是默認的,所以會自動註冊節點。
-ha是高依賴模式,會自動啓用集羣模式-cluster
如果想增加hello-microservice-message的節點,打開新的命令行繼續運行
java -jar name.jar -ha
經過我的測試發現增加hello-consumer-microservice-message是沒用的。
每一次調用localhost:8082都會發送兩個請求到hello-microservice-message節點。
我們發現event loop的一個特性,就是,原來發送到哪個節點後續還會發送到那個節點。
然後我又增加了一個節點,發現了event loop的另一個特性-發送到節點是循環的
本期的小實驗並沒有解決任何實際問題,僅僅是記錄我的想法,很高興浪費你的寶貴時間。