项目github地址:https://github.com/fotocj007/VertxWebApi

一:加入配置文件 mongodb.json

1 compile group: 'io.vertx', name: 'vertx-mongo-client', version: '3.9.8'
1 {
2 "sources": [
3 {"host": "10.0.205.199", "port": 27017, "db_name": "wsdemo","minPoolSize":5,"maxPoolSize": 10}
4 ],
5 "pools": 4
6 }

二:加载配置文件

 1 public class MongoDbConfig extends JsonObjectConfig {
2 public JsonArray sources;
3 public int poolSize;
4
5 public MongoDbConfig(Vertx vertx, String path){
6 super(vertx,path);
7 }
8
9 @Override
10 public void parse(JsonObject jsonObject) {
11 sources = jsonObject.getJsonArray("sources");
12 poolSize = jsonObject.getInteger("pools",8);
13 }
14 }

三:链接mongodb

 1 public class MongoPool {
2 private int poolSize;
3
4 private Vertx vertx;
5
6 private List<JsonObject> sourceList;
7
8 private Map<String,List<MongoClient>> pools;
9
10 public List<String> dbList;
11
12 public MongoPool(Vertx vertx, int poolS, List<JsonObject> sourceList){
13 this.vertx = vertx;
14 this.poolSize = poolS;
15 this.sourceList = sourceList;
16 pools = new HashMap<>(poolS);
17 dbList = new ArrayList<>(2);
18 initPool();
19 }
20
21 private void initPool() {
22 for (JsonObject config : sourceList) {
23 String db = config.getString("db_name");
24
25 String connectionString = String.format("mongodb://%s:%d/%s",
26 config.getString("host"), config.getInteger("port"),
27 db);
28
29 JsonObject options = new JsonObject()
30 .put("connection_string", connectionString)
31 .put("minPoolSize", config.getInteger("minPoolSize"))
32 .put("maxPoolSize",config.getInteger("maxPoolSize"));
33
34 // look for username, password and auth_source
35 Optional.ofNullable(config.getString("username", null))
36 .ifPresent(user -> options.put("username", user));
37 Optional.ofNullable(config.getString("password", null))
38 .ifPresent(pass -> options.put("password", pass));
39
40 List<MongoClient> list = new ArrayList<>();
41 for (int j = 1; j <= poolSize; j++) {
42 list.add(MongoClient.create(vertx, options));
43 }
44
45 dbList.add(db);
46 pools.put(db, list);
47 }
48 }
49
50 public MongoClient getClient(String db){
51 return pools.get(db).get(ThreadLocalRandom.current().nextInt(poolSize));
52 }
53
54 public void close(){
55 for(List<MongoClient> list : pools.values()){
56 for(MongoClient client : list){
57 client.close();
58 }
59 }
60 }
61 }

四:添加个帮助类

 1 public class PlayerMongo{
2 protected static Logger logger = LoggerFactory.getLogger(PlayerMongo.class);
3
4 private final String DB_NAME;
5
6 protected MongoPool mongoDbPool;
7
8 public PlayerMongo(MongoPool mongoPool) {
9 this.DB_NAME = mongoPool.dbList.get(0);
10 this.mongoDbPool = mongoPool;
11 }
12
13 public void findPlayerById(String collection,long playerId,Handler<AsyncResult<PlayerInfo>> handler) {
14 JsonObject jsonQuery = new JsonObject().put("_id",playerId);
15 mongoDbPool.getClient(DB_NAME).findOne(collection, jsonQuery, null, res -> {
16 if (res.succeeded()) {
17 JsonObject reData = res.result();
18
19 long id = reData.getLong("_id",playerId);
20 reData.remove("_id");
21
22 PlayerInfo info = new JsonObject(reData.toString()).mapTo(PlayerInfo.class);
23 info.setId(id);
24
25 handler.handle(Future.succeededFuture(info));
26 }else {
27 handler.handle(Future.failedFuture(res.cause()));
28 logger.error("findById error",res.cause());
29 }
30 });
31 }
32
33 public void updateAndInsert(String collection, long playerId, JsonObject upData, Handler<AsyncResult<Boolean>> handler){
34 JsonObject find = new JsonObject().put("_id",playerId);
35 JsonObject upInsert = new JsonObject()
36 .put("$set",upData);
37
38 //更新,没有时插入
39 mongoDbPool.getClient(DB_NAME).findOneAndUpdateWithOptions(collection, find, upInsert,
40 new FindOptions(),
41 new UpdateOptions().setUpsert(true), res -> {
42 if (res.succeeded()) {
43 handler.handle(Future.succeededFuture(true));
44 } else {
45 handler.handle(Future.failedFuture(res.cause()));
46 logger.error("updateAndInsert error",res.cause());
47 }
48 });
49 }
50 }

五:Dao管理类

 1 public class MongoManager {
2 private MongoPool mongoPool;
3
4 private PlayerMongo playerMongo;
5
6 public MongoManager(MongoPool mySQLPool){
7 this.mongoPool = mySQLPool;
8 init();
9 }
10
11 private void init(){
12 playerMongo = new PlayerMongo(mongoPool);
13 }
14
15 public PlayerMongo getPlayerMongo(){
16 return playerMongo;
17 }
18 }

六:修改configure,初始化mongodb.

 1 public class Configure {
2 private static final Configure ourInstance = new Configure();
3
4 public Configure() {
5 }
6
7 public static Configure getInstance() {
8 return ourInstance;
9 }
10
11 protected Vertx vertx;
12
13 public MysqlConfig mysqlConfig;
14 private MySQLUtil mySQLPool;
15 public DaoManager daoManager;
16
17 private RedisConfig redisConfig;
18 private RedisPool redisPool;
19 public RedisUtil redisUtil;
20
21 private MongoDbConfig mongoDbConfig;
22 private MongoPool mongoPool;
23 public MongoManager mongoManager;
24
25 public void init(Vertx vertx){
26 this.vertx = vertx;
27
28 initHandler();
29
30 loadConfig();
31
32 initDb();
33 initRedis();
34 initMongoDb();
35 }
36
37 private void initHandler(){
38 HandlerManager.getInstance().addHandler(new DemoHandler());
39 }
40
41 /**
42 * 加载db和Redis配置文件
43 */
44 protected void loadConfig(){
45 mysqlConfig = new MysqlConfig(vertx, "res/mysql.json");
46 redisConfig = new RedisConfig(vertx, "res/redis.json");
47 mongoDbConfig = new MongoDbConfig(vertx,"res/mongodb.json");
48 }
49
50 protected void initDb(){
51 List<JsonObject> list = new ArrayList<>();
52 for(int i = 0; i< mysqlConfig.configs.size();i++){
53 list.add(mysqlConfig.configs.getJsonObject(i));
54 }
55 mySQLPool = new MySQLUtil(vertx,2,list);
56
57 daoManager = new DaoManager(mysqlConfig,mySQLPool);
58 }
59
60 /**
61 * 初始化Redis
62 */
63 protected void initRedis(){
64 redisPool = new RedisPool(vertx,redisConfig);
65 redisUtil = new RedisUtil(redisPool);
66 }
67
68 private void initMongoDb(){
69 List<JsonObject> list = new ArrayList<>();
70 for(int i = 0; i< mongoDbConfig.sources.size();i++){
71 list.add(mongoDbConfig.sources.getJsonObject(i));
72 }
73 mongoPool = new MongoPool(vertx,mongoDbConfig.poolSize,list);
74 mongoManager = new MongoManager(mongoPool);
75 }
76
77 public void closeResource(){
78 if(mySQLPool != null){
79 mySQLPool.close();
80 }
81 if(redisPool != null){
82 redisPool.close();
83 }
84
85 if(mongoPool != null){
86 mongoPool.close();
87 }
88 }
89 }

七:测试一下,修改DemoHandler

        PlayerInfo info = new PlayerInfo();
info.setId(3242353465L);
info.setUserName("kkkkkdd");
info.setAge(100); PlayerMongo playerMongo = Configure.getInstance().mongoManager.getPlayerMongo();
playerMongo.updateAndInsert("playerColl",info.getId(),new JsonObject(JsonObject.mapFrom(info).toString()),res -> {
System.out.println(res.result()); //查询
playerMongo.findPlayerById("playerColl",info.getId(),ress -> {
System.out.println(ress); });
});

发起请求,查看输出:

项目结构:

Vertx 接入MongoDB (九)的更多相关文章

  1. MongoDB (九) MongoDB 投影

    mongodb 投影意思是只选择必要的数据而不是选择一个文件的数据的整个.如果一个文档有5个字段,需要显示只有3个,然后选择其中只有3个字段. find() 方法 MongoDB 的find()方法, ...

  2. [转载]MongoDB开发学习 经典入门

    如果你从来没有接触MongoDB或对MongoDB有一点了解,如果你是C#开发人员,那么你不妨花几分钟看看本文.本文将一步一步带您轻松入门. 阅读目录 一:简介 二:特点 三:下载安装和开启服务器 四 ...

  3. MongoDB开发学习

    如果你从来没有接触MongoDB或对MongoDB有一点了解,如果你是C#开发人员,那么你不妨花几分钟看看本文.本文将一步一步带您轻松入门. 阅读目录 一:简介 二:特点 三:下载安装和开启服务器 四 ...

  4. [转载]MongoDB开发学习(1)开天辟地,经典入门

    原文地址:http://www.cnblogs.com/xumingxiang/archive/2012/04/08/2437468.html 如果你从来没有接触MongoDB或对MongoDB有一点 ...

  5. MongoDB开发学习(1)开天辟地,经典入门

    原文地址:http://www.cnblogs.com/xumingxiang/archive/2012/04/08/2437468.html 如果你从来没有接触MongoDB或对MongoDB有一点 ...

  6. MongoDB入门学习笔记之简介与安装配置

    一.MongoDB简介 1.文档数据库 MongoDB是一款开源的文档型非关系数据库,具有高性能.高可靠性和自动扩展等特点.MongoDB中的每一条记录是一个文档,其数据存储结构为键/值对,类似JSO ...

  7. 5-3 掌握 egg.js + 云 mongodb

    1 egg.js 1.1 初始化 初始化和项目启动方法 # 初始化 $ mkdir egg-example && cd egg-example $ npm init egg --typ ...

  8. Nodejs电影建站开发实例(上)

    网站环境:使用express框架.bootstrap样式.jade模板.mongoose数据库 npm insatll express -g npm insatll jada -g npm insat ...

  9. c++利用jsoncpp libcurl 构造http 包(原)

    我们手游要接入uc九游进行测试,要用http向uc那边的sdk 服务器post  json数据. 虽然他们提供了php,java还有c#的服务端demo,但是我们服务器是C++写的,我实在不想中间再转 ...

  10. 《.NETer提高效率——环境部署》

    初衷 兵马未动,粮草先行. 电脑坏了or换工作等需要重装系统. 开发运维一把梭. 与时俱进. 记忆力差,需要文字记录. 因为懒... 目的 通过学习 Linux+docker+kubernetes+C ...

随机推荐

  1. RabbitMQ 延迟任务(限时订单) 思路

    一.场景 我们经常会碰见,一个需求就是,发送一条指令(消息),延迟一段时间执行,比如说常见的淘宝当下了一个订单后,订单支付时间为半个小时,如果半个小时没有支付,则关闭该订单.当然实现的方式有几种,今天 ...

  2. 【Docker】常用服务镜像安装

    Docker常用安装 总体步骤 搜索镜像:docker search xxx 拉取镜像:docker pull xxx 查看镜像:docker images 启动镜像:docker run xxx 停 ...

  3. 【Java】枚举类和注解

    一.枚举类的使用 1. 枚举类的说明: 枚举类的理解:类的对象只有有限个,确定的.我们称此类为枚举类 当需要定义一组常量时,强烈建议使用枚举类 枚举类的实现: JDK 5.0以前需要自定义 JDK 5 ...

  4. 【Java】Java实现简单异或加密

    Java实现简单异或加密 零.需求 在做一个简单的Web项目,需要把账号密码以Cookie的形式存储到浏览器中记住,不能直接明文,故需要一种简单的加密方式,想到了异或加密. 壹.实现 /** * 异或 ...

  5. vue 水印插件

    vue 水印插件 插件: directives.js import Vue from 'vue' /** * author: zuokun * 水印 * text:水印文字 * font:字体 * t ...

  6. Robot Framework全局变量设置

    脚本在每次执行的时候,自定义输入的内容,每次均需要手动去修改 比如,添加商品,上一次执行设置的商品名称为"商品1",这次再执行"商品1"就会导致冲突 如果仅仅是 ...

  7. 在 Go 语言中,构造一个并发安全的 map 集合

    Map 集合是 Go 中提供的一个 KV 结构的数据类型,对它的操作在实际的开发中应该是非常多的,不过它不是一个线程安全的. 1 .Map 不是线程安全的 编写下面的测试代码: func TestUn ...

  8. 解决React Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?

    问题 当我使用如下方式调用组件子组件UploadModal并且绑定Ref时React报错"Warning: Function components cannot be given refs. ...

  9. DDD领域驱动大纲讲义

    DDD领域驱动模型 什么是领域?什么是领域模型? 没有丰富的领域知识能做出复杂的银行业业务软件吗 ? 没门 . 答案永远是否定的 . 那么谁 了解银行业业务 ? 软件架构师吗 ? 不 , 他只是在使用 ...

  10. C#网络编程(一)----DNS/TCP/UDP协议

    简介 计算机网络是指将分布在不同地理位置的计算机系统.设备通过通信线路和设备连接起来,遵循共同的通信协议,以实现 数据传输.资源共享.协同工作 的系统 .它是现代信息技术的核心基础设施,支撑着互联网. ...