All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.anwen.mongo.conn.CollectionManager Maven / Gradle / Ivy

There is a newer version: 2.1.5
Show newest version
package com.anwen.mongo.conn;

import com.anwen.mongo.cache.global.CollectionLogicDeleteCache;
import com.anwen.mongo.factory.MongoClientFactory;
import com.anwen.mongo.handlers.collection.AnnotationOperate;
import com.anwen.mongo.logic.UnClassCollection;
import com.mongodb.client.MongoCollection;
import org.bson.Document;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 连接管理器
 *
 * @author JiaChaoYang
 * @date 2023-12-28 11:13
 **/
public class CollectionManager {

    /**
     * 缓存mongoCollection
     *
     * @date 2023/12/28 10:58
     */
    private final Map> collectionMap = new ConcurrentHashMap<>();


    private final String database;

    public CollectionManager(String database) {
        this.database = database;
    }

    /**
     * 设置一个连接
     *
     * @author JiaChaoYang
     * @date 2023/12/28 11:20
     */
    public void setCollectionMap(String key, MongoCollection value) {
        collectionMap.put(key, value);
    }

    public MongoCollection getCollection(Class clazz) {
        return getCollection(AnnotationOperate.getCollectionName(clazz));
    }

    public MongoCollection getCollection(String collectionName) {
        MongoCollection mongoCollection;
        // 检查连接是否需要重新创建
        if (!this.collectionMap.containsKey(collectionName)) {
            mongoCollection = new ConnectMongoDB(MongoClientFactory.getInstance().getMongoClient(), database, collectionName).open();
            this.collectionMap.put(collectionName, mongoCollection);
            CollectionLogicDeleteCache.mapperClassByCollection(mongoCollection.getNamespace().getFullName(), UnClassCollection.class);
        } else {
            mongoCollection = this.collectionMap.get(collectionName);
        }
        return mongoCollection/*.withCodecRegistry(RegisterCodecUtil.getCodecCacheAndDefault())*/;
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy