【发布时间】:2020-12-24 21:36:49
【问题描述】:
我有一个带有 MongoDB 的基本独立 Spring Boot 应用程序。但是,从数据库中检索数据时速度非常慢。例如,从产品集合中检索五个文档(全部)需要 2.5 秒,如下图(实体类),没有 getter 和 setter。
@Document(collection = "products")
public class Product {
private double itemPrice;
private int quantity;
@Indexed(unique = true)
private String name;
@Id
private String productId;
@DBRef
private Set<ProductTransaction> productTransactions;
}
仓库类如下图:
@Repository
public interface ProductRepository extends MongoRepository<Product, String> {
}
服务类如下图:
@Service
public class ProductServiceImpl implements ProductService{
@Autowired
ProductRepository productRepository;
public List<Product> getProducts() {
startTime = System.currentTimeMillis();
Iterable<Product> products = productRepository.findAll();
endTime = System.currentTimeMillis();
System.out.println("Find all products: " + (endTime - startTime));
return products;
}
}
application.properties 文件:
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=productDB
spring.data.mongodb.auto-index-creation=false
pom.xml如下图:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.3.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>com.spring.mongodb.ims</groupId>
<artifactId>ims-desktop-application</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>ims-desktop-application</name>
<description>This is an app for managing sales and inventories</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.modelmapper</groupId>
<artifactId>modelmapper</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
请注意,相同的查询在 mongo shell 中执行时非常快
db.products.find()
我将非常感谢任何帮助,以解开来自 Spring Boot 应用程序的查询为什么非常慢。
【问题讨论】:
-
仅供参考:尽量不要使用@DBRef。但这不是延迟的原因
-
@varman 你知道@DBRef 的替代品吗?到目前为止,我的调查表明它是造成延误的原因。
-
我们使用聚合来连接两个集合。看看
$lookup
标签: java spring mongodb spring-boot spring-data