IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 网络协议 -> http连接mongoDb -> 正文阅读

[网络协议]http连接mongoDb

建立连接工具:

public class MongoConn {


    /**
     * 需要密码认证方式连接
     */
    public static MongoClient getConnect(String ip, String port, String userName, String password, String dataBaseName) {
        List<ServerAddress> adds = new ArrayList<>();
        //ServerAddress()两个参数分别为 服务器地址 和 端口
        ServerAddress serverAddress = new ServerAddress(ip, Integer.parseInt(port));
        adds.add(serverAddress);

        //List<MongoCredential> credentials = new ArrayList<>();
        //MongoCredential.createScramSha1Credential()三个参数分别为 用户名 数据库名称 密码
        MongoCredential mongoCredential = MongoCredential.createScramSha1Credential(userName, dataBaseName, password.toCharArray());
        //credentials.add(mongoCredential);
        MongoClientOptions mongoClientOptions = new MongoClientOptions.Builder()
                .maxConnectionLifeTime(60000)
                .maxWaitTime(10000)
                .maxConnectionIdleTime(10000)
                .heartbeatConnectTimeout(1000)
                .serverSelectionTimeout(30000).build();
        //通过连接认证获取MongoDB连接
        MongoClient mongoClient = new MongoClient(adds, mongoCredential, mongoClientOptions);
        //返回连接数据库对象
        return mongoClient;
    }

}

引用:

    /**
     * 缓存所有项目包数
     */
    @Scheduled(cron = "0 0 * * * *")
    public void updateMongoDbPackageData() {
        //获取所有项目
        Map<String, String> map = SynServerInfoTask.projectInfos;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (map.size() > 0) {
            log.info("定时任务开始更新所有项目数据包缓存,更新时间:{}", simpleDateFormat.format(new Date()));
            Set<Map.Entry<String, String>> entries = map.entrySet();
            long systemTime = System.currentTimeMillis();
            double sub = DataUtils.sub(systemTime, 1000 * 60 * 60);
            String startTime = simpleDateFormat.format(new Date((long) sub));
            String endTime = simpleDateFormat.format(new Date((systemTime)));
            for (Map.Entry<String, String> sr : entries) {
                String key = sr.getKey();
                String value = sr.getValue();
                MongoClient mongoClient = null;
                MongoCursor<Document> periodData = null;
                try {
                    List<String> list = new LinkedList<>();
                    JSONObject mongoServerInfo = serverInfoBaseService.getServerInfo(key, BaseConstants.mongodbType);
                    if (StringUtils.isBlank(mongoServerInfo.getString(BaseConstants.databaseName))) {
                        continue;
                    }
                    mongoClient = MongoConn.getConnect(mongoServerInfo.getString(BaseConstants.ip), mongoServerInfo.getString(BaseConstants.port), mongoServerInfo.getString(BaseConstants.username), mongoServerInfo.getString(BaseConstants.password), mongoServerInfo.getString(BaseConstants.databaseName));
                    MongoDatabase database = mongoClient.getDatabase(mongoServerInfo.getString(BaseConstants.databaseName));
                    periodData = MongodbUtil.getPeriodData(database, mongoServerInfo.getString(BaseConstants.tableName), startTime, endTime, "systime", "0", "systime");
                    while (periodData.hasNext()) {
                        Document next = periodData.next();
                        list.add(next.getString("systime"));
                    }
                    String projectKey = key.concat(BaseConstants.DATAPACKAGE);
                    String str = (String) redisTemplate.opsForValue().get(projectKey);
                    if (null != str) {
                        List<String> timeList = Arrays.asList(str.split(",")).stream().map(s -> (s.trim())).collect(Collectors.toList());
                        list.addAll(timeList);
                    }
                    String jsonStr = StringUtils.join(list.toArray(), ",");
                    redisTemplate.opsForValue().set(projectKey, jsonStr);
                    log.info("定时任务更新时间包数据缓存成功,项目名:{},时间:{}", value, simpleDateFormat.format(new Date()));
                } catch (CommonException e) {
                    e.printStackTrace();
                } finally {
                    if (null != periodData) {
                        periodData.close();
                    }
                    if (null != mongoClient) {
                        mongoClient.close();
                    }
                }
            }
            log.info("定时任务更新时间包数据缓存结束");
        }
    }

工具类:

public class MongodbUtil {

    /**
     * 获取多时间点mongo数据
     * @param mongoDatabase
     * @param collectionName
     * @param timeList
     * @param dataType
     * @return
     */
    public static MongoCursor<Document> getMulTimeData(MongoDatabase mongoDatabase, String collectionName, List<String> timeList, String dataType){
        Bson systimes = Filters.in("systime", timeList);
        Bson dateType = Filters.eq("datatype", dataType);
        Bson queryBson = Filters.and(systimes, dateType);
        FindIterable<Document> documentIterable = mongoDatabase.getCollection(collectionName).find(queryBson);
        MongoCursor<Document> cursor = documentIterable.iterator();
        return cursor;
    }

    /**
     * 获取指定时间段mongo数据
     * @param mongoDatabase
     * @param collectionName
     * @param startTime
     * @param endTime
     * @param orderColumn
     * @param dataType
     * @param fieldName
     * @return
     */
    public static MongoCursor<Document> getPeriodData(MongoDatabase mongoDatabase, String collectionName, String startTime, String endTime, String orderColumn, String dataType,String fieldName ) {
        Bson stimeBson = Filters.gte("systime", startTime);
        Bson etimeBson = Filters.lte("systime", endTime);
        Bson dateType = Filters.eq("datatype", dataType);
        BasicDBObject field = new BasicDBObject();
        field.put(fieldName,1);
        Bson sort = Sorts.ascending(orderColumn);
        Bson queryBson = Filters.and(stimeBson, etimeBson, dateType);
        FindIterable<Document> documentIterable = mongoDatabase.getCollection(collectionName).find(queryBson).projection(field).sort(sort);
        MongoCursor<Document> cursor = documentIterable.iterator();
        return cursor;
    }

  网络协议 最新文章
使用Easyswoole 搭建简单的Websoket服务
常见的数据通信方式有哪些?
Openssl 1024bit RSA算法---公私钥获取和处
HTTPS协议的密钥交换流程
《小白WEB安全入门》03. 漏洞篇
HttpRunner4.x 安装与使用
2021-07-04
手写RPC学习笔记
K8S高可用版本部署
mySQL计算IP地址范围
上一篇文章      下一篇文章      查看所有文章
加:2021-10-22 11:17:36  更:2021-10-22 11:18:50 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年7日历 -2024/7/3 13:39:39-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码