• Vertx 接入MongoDB (九)


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

    一:加入配置文件 mongodb.json

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

    二:加载配置文件

     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 }
    View Code

    三:链接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 }
    View Code

    四:添加个帮助类

     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 }
    View Code

    五: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 }
    View Code

    六:修改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 }
    View Code

    七:测试一下,修改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);
    
                });
            });

    发起请求,查看输出:

     

    项目结构:

  • 相关阅读:
    项目代码风格要求
    命名规范
    五招四十二式
    PMBok项目管理
    敏捷软件开发要点
    设计一种前端数据延迟加载的jQuery插件(2)
    为什么Java byte 类型的取值范围是-128~127 (转)
    Xcode编译时出现cannot run using the selected device提示
    mac下的常用操作
    iOS用AVAudioPlayer播放m4a音频
  • 原文地址:https://www.cnblogs.com/cj8988/p/15040216.html
Copyright © 2020-2023  润新知