前回の続き
から、なんとなくではあるが完成した。
前回起きた、「io.vertx~mod-mongo-persistor~2.1.1-SNAPSHOT」 モジュールが自動的に Downloading… となる件は、
そういったvertxの素晴らしい仕様らしく 設定は conf/repos.txt に存在していた。
さて、結果として、通信には SockJS を用いる事とし、下記の構成で vertxによるmongodb接続でのデータ取得から保存までを行うことが出来た。
sockJSServer.bridge の辺りの理解が乏しく、であるから「なんとなく」という事にしておく。
conf.js (vertx で必要)
{ "mongo-persistor": { "address": "vertx.mongopersistor", "host": "localhost", "port": 27017, "pool_size": 10, "db_name": "testdata" } }
app.js (vertx で必要)
var vertx = require('vertx'); var container = require('vertx/container'); var console = require('vertx/console'); var server = vertx.createHttpServer(); var httpServer = vertx.createHttpServer(); var sockJSServer = vertx.createSockJSServer(httpServer); var config = container.config; var logger = container.logger;
logger.info(JSON.stringify(config[“mongo-persistor”]));
container.deployModule(‘io.vertx~mod-mongo-persistor~2.1.1-SNAPSHOT’, config[“mongo-persistor”], function(err, deployID) {
if (!err) {
console.log(“The verticle has been deployed, deployment ID is ” + deployID);
} else {
console.log(“Deployment failed! ” + err.getMessage());
}
});
sockJSServer.bridge({prefix : ‘/eventbus’},
[
{
address : ‘vertx.mongopersistor’
},
{
address : ‘vertx.mongopersistor’,
match : {
action : ‘find’,
collection : ‘testdata’
}
},
{
match : {
wibble: ‘foo’
}
}
],
[{}]
);
httpServer.listen(8081);
server.requestHandler(function(req) {
req.response.sendFile(‘./web’+req.uri());
}).listen(8080, ‘localhost’);
index.html (フロントWebブラウザで実行)
コンソールから下記で vertx を起動。
vertx run app.js -conf conf.json
ブラウザで下記にアクセスし、ChromeのJavaScriptコンソールを見てみると。
http://localhost:8080/index.html
例として、下記の様に表示される。(mongodb側にデータが何もない場合には、1回目の表示ではこうはならず、2回目以降での例なのでご注意)
mongodb内の状態により、vertx側で下記が表示される事がある。
Exception in Java verticle org.vertx.java.core.VertxException: Cannot have objects of class class org.bson.types.ObjectId in JSON
この問題は、BSONデータを mod-mongo-persistor によって正確に変換できない場合のようである。
私の場合は、_id キーに対して “ObjectId(“5388b65aec58c23549631000”)” というBSONデータが既に設定されている場合に起きていた。
mongo コマンドからのsave() を行った場合など、_id にそのような値が設定されていたのでそれが原因だったようである。
ちなみに、今回 EventBus を介した save では _id がそのようになることは無かった。
上記の、http://localhost:8080/index.html は、実行と同時に、返却されたオブジェクトを新たに mongodb へ登録しているので、リロードの連打によりレコードが増えていく様になっている。
フロント周りは色々とカスタマイズすれば、データ連携が出来そうになってきた。
ちなみに、今回は、
http://localhost:8080/ は HTTPサーバー
http://localhost:8081/ は EventBus
として利用している。
ここまでで色々と理解が深まったことも有り、
やりたいことへ、なんとなく近づいたようである。
以上、
ご意見などございましたらよろしくお願いいたします。
コメントは受け付けていません