MongDB级别写入计数

时间:2016-08-19 20:52:09

标签: java mongodb spring-data-mongodb mongodb-java

我需要弄清楚MongoDB在过去一小时内对读取执行了多少次写入。

是否有一种简单的方法可以找到创建警报所需的这些统计数据。如果解决方案是命令驱动的或基于Java的,那将非常有用。

1 个答案:

答案 0 :(得分:0)

挖掘MongoDB jdbc驱动的源代码后。我终于能够得到所需要的东西了。下面是它的代码

    public class MongoJmxStat {

    private MongoClient mongo;

    public MongoJmxStat(MongoClient mongo) {
        this.mongo = mongo;
    }

    public CommandResult getServerStatus() {
        CommandResult result = getDb("mongoDB").command("serverStatus");
        if (!result.ok()) {

            throw new MongoException("could not query for server status.  Command Result = " + result);
        }

        return result;
    }

    public DB getDb(String databaseName) {
        return MongoDbUtils.getDB(mongo, databaseName);
    }

    private int getOpCounter(String key) {
        DBObject opCounters = (DBObject) getServerStatus().get("opcounters");
        return (Integer) opCounters.get(key);
    }

    @ManagedMetric(metricType = MetricType.COUNTER, displayName = "Write operation count")
    public int getWriteCount() {
        return getOpCounter("insert") + getOpCounter("update") + getOpCounter("delete");
    }

    @ManagedMetric(metricType = MetricType.COUNTER, displayName = "Read operation count")
    public int getReadCount() {
        return getOpCounter("query") + getOpCounter("getmore");
    }

}