|
@@ -0,0 +1,49 @@
|
|
|
+package ieven.server.webapp.infrastructure;
|
|
|
+
|
|
|
+import com.mongodb.BasicDBObject;
|
|
|
+import com.mongodb.client.model.IndexModel;
|
|
|
+import com.mongodb.client.model.IndexOptions;
|
|
|
+import org.springframework.beans.factory.annotation.Autowired;
|
|
|
+import org.springframework.boot.CommandLineRunner;
|
|
|
+import org.springframework.data.mongodb.core.MongoTemplate;
|
|
|
+import org.springframework.stereotype.Component;
|
|
|
+
|
|
|
+import java.util.ArrayList;
|
|
|
+import java.util.List;
|
|
|
+import java.util.concurrent.TimeUnit;
|
|
|
+
|
|
|
+/**
|
|
|
+ * 在系统启动的时候自动监测并且创建索引
|
|
|
+ */
|
|
|
+@Component
|
|
|
+public class InitDB implements CommandLineRunner {
|
|
|
+ @Autowired
|
|
|
+ private MongoTemplate mongoTemplate;
|
|
|
+
|
|
|
+ @Override
|
|
|
+ public void run(String... args) throws Exception {
|
|
|
+ tryCreateIndex("data", "fileId", -1);
|
|
|
+ tryCreateIndex("fields", "fileId", -1);
|
|
|
+ tryCreateIndex("logical_file", "modelId", -1);
|
|
|
+ tryCreateIndex("model", "createTime", -1);
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 创建索引
|
|
|
+ *
|
|
|
+ * @param collection 集合名字
|
|
|
+ * @param field 字段名字
|
|
|
+ * @param order 1正序,-1倒序
|
|
|
+ */
|
|
|
+ private void tryCreateIndex(String collection, String field, Object order) {
|
|
|
+ List<IndexModel> indexModels = new ArrayList<>();
|
|
|
+ BasicDBObject index = new BasicDBObject();
|
|
|
+ index.put(field, order);
|
|
|
+ IndexOptions indexOptions = new IndexOptions();
|
|
|
+ indexOptions.background(true);
|
|
|
+ indexOptions.name("index_" + field);
|
|
|
+ indexOptions.expireAfter(3600L, TimeUnit.SECONDS);
|
|
|
+ indexModels.add(new IndexModel(index));
|
|
|
+ mongoTemplate.getCollection(collection).createIndexes(indexModels);
|
|
|
+ }
|
|
|
+}
|