`

Mongodb 原生操作类

 
阅读更多
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.UpdateManyModel;
import com.mongodb.client.model.geojson.Point;
import com.mongodb.client.model.geojson.Polygon;
import com.mongodb.client.model.geojson.Position;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.bson.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 原生java操作MongoDB工具类
 *
 * @author: lanweixing
 * @create: 2019-05-15 14:06
 **/
@Component
public class MongodbManageHandler {

    private final static Logger logger = LoggerFactory.getLogger(MongodbManageHandler.class);

    @Value("${r.mongo.dbname}")
    private String dbName ;

    @Autowired
    private MongoClient mongodbClient;

    /**
     * 获取Mongodb集合
     *
     * @param collectionName
     * @return
     */
    public MongoCollection doGetMongoCollection(String collectionName){
        MongoDatabase database = this.mongodbClient.getDatabase(this.dbName);
        if(database != null){
            return database.getCollection(collectionName);
        }
        return null ;
    }

    /**
     * 通过经纬度获取区域ID
     * 一个经纬度只能在一个区域内
     *
     *
     * @param lng
     * @param lat
     * @return
     */
    public List<Long> doGetAreaIdByLngAndLat(Double lng, Double lat){
        Preconditions.checkNotNull(lng,"经度不能为空");
        Preconditions.checkNotNull(lat,"纬度不能为空");
        Preconditions.checkState(lng != 0,"经度不能为0");
        Preconditions.checkState(lat != 0,"纬度不能为0");
        Stopwatch stopwatch = Stopwatch.createStarted();
        List<Long> areaIds = Lists.newArrayList();
        try{
            MongoCollection mongoCollection = this.doGetMongoCollection("cityServiceArea");
            if(mongoCollection != null){
                FindIterable findIterable = mongoCollection.find(Filters.geoIntersects("geo",new Point(new Position(lng,lat))));
                if(findIterable != null){
                    Document document = (Document)findIterable.first();
                    if(document != null){
                        areaIds.add((long)document.get("_id"));
                    }
                }
            }
            logger.info("【SBS】通过经纬度获取区域值ID:{} 耗时:{}", JSON.toJSONString(areaIds),stopwatch.stop());
            return areaIds;
        }catch (Exception e){
            logger.info("【SBS】通过经纬度获取区域ID出错,{}",e);
            throw new BusinessException(ErrorCodeConstants.BUSINESS_ERROR, "通过经纬度获取区域异常");
        }
    }

    /**
     * 批量插入区域信息
     *
      * @param cityServiceAreas
     */
    public void doBatchInsertCityServiceArea(List<CityServiceArea> cityServiceAreas){
        Stopwatch stopwatch = Stopwatch.createStarted();
        if(CollectionUtils.isNotEmpty(cityServiceAreas)){
            MongoCollection mongoCollection = this.doGetMongoCollection("cityServiceArea");
            if(mongoCollection != null){
                try {
                    List<Document> saveCollections = Lists.newArrayList();
                    for(CityServiceArea cityServiceArea : cityServiceAreas){
                        if(cityServiceArea != null){
                            Document document = new Document();
                            document.append("_id", cityServiceArea.getId());
                            document.append("_class","com.hk.sbs.mongodb.CityServiceAreaMongo");
                            if(StringUtils.isNotEmpty(cityServiceArea.getServiceArea())){
                                document.append("geo",new Polygon(Arrays.stream(cityServiceArea.getServiceArea().split("@")).map(lonLats -> lonLats.split(",")).map(lonLat -> new Position(Double.parseDouble(lonLat[0]), Double.parseDouble(lonLat[1]))).collect(Collectors.toList())));
                            }
                            document.append("cityCode",cityServiceArea.getCityCode());
                            document.append("cityName",cityServiceArea.getCityName());
                            saveCollections.add(document);
                        }
                    }
                    mongoCollection.insertMany(saveCollections);
                    logger.info("【SBS】批量保存区域数据耗时:{}",stopwatch.stop());
                } catch (Exception e) {
                    logger.info("【SBS】批量保存区域数据异常,{}",e);
                    throw new BusinessException(ErrorCodeConstants.BUSINESS_ERROR, "批量保存区域数据异常");
                }
            }
        }
    }

    /**
     * 批量更新区域信息
     *
     * @param cityServiceAreas
     */
    public void doBatchUpdateCityServiceArea(List<CityServiceArea> cityServiceAreas){
        Stopwatch stopwatch = Stopwatch.createStarted();
        if(CollectionUtils.isNotEmpty(cityServiceAreas)){
            MongoCollection mongoCollection = this.doGetMongoCollection("cityServiceArea");
            if(mongoCollection != null){
                try {
                    List<UpdateManyModel<Document>> updateCollections = Lists.newArrayList();
                    for(CityServiceArea cityServiceArea : cityServiceAreas){
                        if(cityServiceArea != null){
                            Document queryDocument = new Document("_id", cityServiceArea.getId());
                            Document setDocument = new Document()
                            .append("_class","com.hk.sbs.mongodb.CityServiceAreaMongo");
                            if(StringUtils.isNotEmpty(cityServiceArea.getServiceArea())){
                                setDocument.append("geo",new Polygon(Arrays.stream(cityServiceArea.getServiceArea().split("@")).map(lonLats -> lonLats.split(",")).map(lonLat -> new Position(Double.parseDouble(lonLat[0]), Double.parseDouble(lonLat[1]))).collect(Collectors.toList())));
                            }
                            setDocument.append("cityCode",cityServiceArea.getCityCode());
                            setDocument.append("cityName",cityServiceArea.getCityName());
                            updateCollections.add(new UpdateManyModel<Document>(queryDocument,new Document("$set",setDocument)));
                        }
                    }
                    mongoCollection.bulkWrite(updateCollections);
                    logger.info("【SBS】批量更新区域数据耗时:{}",stopwatch.stop());
                } catch (Exception e) {
                    logger.info("【SBS】批量更新区域数据异常,{}",e);
                    throw new BusinessException(ErrorCodeConstants.BUSINESS_ERROR, "批量更新区域数据异常");
                }
            }
        }
    }
}



分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics