在Spring Boot中简单使用MongoDB

在Spring Boot中简单使用MongoDB

一、使用背景

  • 项目需求监控手机端的微信消息记录,众多消息记录的产生。很明显,关系型数据库已经不能满足,所以就开始尝试使用基于分布式文件存储的数据库——MongoDB来存储大量的消息记录。

二、项目结构

在Spring Boot中简单使用MongoDB_第1张图片

三、代码如下

1、pom.xml


		
			org.springframework.boot
			spring-boot-starter-data-mongodb
		

2、application.properties

spring.data.mongodb.uri=mongodb://127.0.0.1:27017/db

3、ChatRecDao

package com.dbsun.dao.mgdb;

import com.dbsun.entity.mgdb.ChatRecEntity;
import com.dbsun.entity.system.Page;
import com.dbsun.entity.system.PageData;

import java.util.List;

public interface ChatRecDao {

    public int addMsg(ChatRecEntity entity);

    public int addMsgs(List list);

    public List findChatLogsByTP();

    public List getPageMgOfResContsLst(Page page);

    public List getTkSendOrRecCount(PageData pd);

    public List getWrmWordRecLst(PageData pd);

}

4、ChatRecDaoImpl

package com.dbsun.daoImpl.mgdb;

import com.dbsun.dao.mgdb.ChatRecDao;
import com.dbsun.entity.mgdb.ChatRecEntity;
import com.dbsun.entity.system.Page;
import com.dbsun.entity.system.PageData;
import com.dbsun.util.DateUtil;
import com.dbsun.util.PCSensitiveEventConst;
import com.dbsun.util.Tools;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository("chatRecDao")
public class ChatRecDaoImpl implements ChatRecDao {

    @Autowired
    private MongoTemplate mongoTemplate;

    public int addMsg(ChatRecEntity entity) {

        int ret = 0;
        try {
            mongoTemplate.insert(entity, "chat_log");

            ret = 1;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return ret;
    }

    public int addMsgs(List list) {

        int ret = 0;

        try {

            mongoTemplate.insertAll(list);

            ret = 1;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return ret;
    }

    public List findChatLogsByTP() {
        return mongoTemplate.find(new Query(Criteria.where("chat_cont_tp").is(1)).limit(10), ChatRecEntity.class);
    }

    @Override
    public List getPageMgOfResContsLst(Page page) {

        PageData pd = page.getPd();

        // 默认昨天的数据
        Long dateStart = DateUtil.getYesterdayStartStamp();
        Long dateEnd = DateUtil.getTodayStartStamp();

        if (!Tools.isObjEmpty(pd.get("dateStart"))
                && !Tools.isObjEmpty(pd.get("dateEnd"))) {
            dateStart = Long.parseLong(pd.getString("dateStart"));
            dateEnd = Long.parseLong(pd.getString("dateEnd"));

        }

        // 要查询的目标
        String aimId = pd.getString("aimId");

        // 分页要求
        Query query = page.getQuery();

        Criteria tmCri = new Criteria();
        tmCri.andOperator(
                Criteria.where("chat_send_tm").gte(dateStart),
                Criteria.where("chat_send_tm").lt(dateEnd)
        );

        Criteria fAndTCri_1 = new Criteria();
        fAndTCri_1.andOperator(
                Criteria.where("chat_from").is(aimId),
                Criteria.where("chat_to").ne(aimId)
        );

        Criteria fAndTCri_2 = new Criteria();
        fAndTCri_2.andOperator(
                Criteria.where("chat_from").ne(aimId),
                Criteria.where("chat_to").is(aimId)
        );

        Criteria fAndTOrCri = new Criteria();
        fAndTOrCri.orOperator(
                fAndTCri_1,
                fAndTCri_2
        );

        Criteria matchCri = new Criteria();
        matchCri.andOperator(
                tmCri,
                fAndTOrCri
        );

        Sort sort = new Sort(Sort.Direction.DESC, "chat_send_tm");

        Aggregation aggregation = Aggregation.newAggregation(

                Aggregation.match(matchCri),
                Aggregation.group("chat_from", "chat_to")
						// 最新的一条消息
                        .last("$chat_cont").as("lastedCont")
                        .last("$_id").as("id")
                        .last("$chat_from").as("chat_from")
                        .last("$chat_to").as("chat_to")
                        .last("$chat_send_tm").as("chat_send_tm")
                        .last("$chat_cont_tp").as("chat_cont_tp")
                        .last("$chat_tp").as("chat_tp")
                        .last("$chat_from_name").as("chat_from_name")
                        .last("$chat_to_name").as("chat_to_name")
                        .last("$chat_translate").as("chat_translate")
                        .last("$chat_from_note").as("chat_from_note")
                        .last("$chat_to_note").as("chat_to_note"),
                Aggregation.sort(sort),
                Aggregation.limit(page.getShowCount())

        );

        AggregationResults agr = mongoTemplate.aggregate(aggregation, "chat_log", PageData.class);
        List agrLst = agr.getMappedResults();
        return agrLst;
    }

    @Override
    public List getTkSendOrRecCount(PageData pd) {

        // 默认昨天的数据
        Long dateStart = DateUtil.getYesterdayStartStamp();
        Long dateEnd = DateUtil.getTodayStartStamp();

        if (!Tools.isObjEmpty(pd.get("dateStart"))
                && !Tools.isObjEmpty(pd.get("dateEnd"))) {
            dateStart = Long.parseLong(pd.getString("dateStart"));
            dateEnd = Long.parseLong(pd.getString("dateEnd"));

        }

        // 时间范围
        Criteria cri = new Criteria();
        cri.andOperator(
                Criteria.where("chat_send_tm").gte(dateStart),
                Criteria.where("chat_send_tm").lt(dateEnd),
				// 只统计个人消息
                Criteria.where("chat_tp").is(2), 
                // 类似MySQL的like "name%"
                Criteria.where("DEPT_LAYERORDER").regex("^" + pd.getString("DEPT_LAYERORDER"))
        );

        Aggregation aggregation = Aggregation.newAggregation(

                Aggregation.match(cri),
				// 按发送接收类型分组
                Aggregation.group("ISSEND") 
                        .count().as("count")

        );

        AggregationResults agr = mongoTemplate.aggregate(aggregation, "chat_log", PageData.class);

        return agr.getMappedResults();
    }
 
    @Override
    public List getWrmWordRecLst(PageData pd) {

        String maxRecId = pd.getString("maxRecId");
        String wrmWord = pd.getString("wrmWord");

        Query query = new Query();

        // 排序,并且Like chat_cont列
        Criteria andCri = new Criteria();
        andCri.andOperator(
                // ObjectId的查询
                Criteria.where("_id").gt(new ObjectId(maxRecId)),
                Criteria.where("chat_cont").regex(wrmWord)
        );

        query.addCriteria(andCri);
        // ID从小到大排序 此时的排序肯定是投影之后再排序,但是选择出大于id的数据就OK
        Sort sort = new Sort(Sort.Direction.ASC, "_id");

        query.with(sort);

        // 返回符合该敏感词的消息记录
        List list = mongoTemplate.find(query, PageData.class, "chat_log");

        // 把ObjectId转为字符串
        for (PageData recPd:list) {
            recPd.put("_id", recPd.get("_id").toString());
        }

        return list;
    }

    @Override
    public List getMgChatRecLst(String _id) {
        Query query = new Query();
        if (_id != null) {
            query.addCriteria(Criteria.where("_id").gt(new ObjectId(_id)));
        }
        query.addCriteria(Criteria.where("chat_cont_tp")
                .in(
                        PCSensitiveEventConst.RED_ENVELOPE_SEND_REQUEST.getCode(),
                        PCSensitiveEventConst.RED_ENVELOPE_RECEIVE_REQUEST.getCode(),
                        PCSensitiveEventConst.TRANSFER_SEND_REQUEST.getCode(),
                        PCSensitiveEventConst.TRANSFER_SEND_REQUEST.getCode(),
                        PCSensitiveEventConst.BUSINESS_CARD_SEND.getCode(),
                        PCSensitiveEventConst.BUSINESS_CARD_RECEIVE.getCode(),
                        PCSensitiveEventConst.POSITION_SEND_REQUEST.getCode(),
                        PCSensitiveEventConst.POSITION_RECEIVE_REQUEST.getCode()
                ));
        query.with(new Sort(Sort.Direction.ASC, "_id"));
        return mongoTemplate.find(query, PageData.class, "chat_log");
    }

}

5、ChatRecService

  • 调用dao层接口即可

6、注意

  • MongoDB的“_id”为ObjectId在程序中需要对其进行相应的转换MongoDB的“_id”为ObjectId在程序中需要对其进行相应的转换

你可能感兴趣的:(MongoDB)