Skip to main content
 首页 » 编程设计

spring-boot之开发占地面积更小的Spring Boot应用程序

2024年12月31日14haluo1

为了使我们的微服务(以 Spring 启动方式开发)可以在Cloud Foundry上运行,并且占用空间较小,我们正在寻求实现这一目标的最佳方法。

朝这个方向的任何输入或指针将是最受欢迎的。

当然,最好总是从最低限度的依赖关系开始向上构建应用程序,然后仅在需要时再添加。是否有更多的良好做法可遵循,以进一步减小应用程序的大小?

请您参考如下方法:

以下是一些关于如何使用Spring Boot达到较小足迹的个人想法。您的问题过于广泛,以致于在任何其他情况下都无法考虑这些建议。我不确定在大多数情况下是否要遵循这些原则,它只是回答“如何实现更小的占地面积”。

(1)仅指定必需的依赖项

我个人不会为此担心,但是如果目标是减小占用空间,则可以避免使用starter-* dependencies。仅指定您实际使用的依赖项。

避免此:

<dependency> 
    <groupId>org.springframework.boot</groupId> 
    <artifactId>spring-boot-starter-data-jpa</artifactId> 
</dependency> 

In my sample project, the artifact produced with starter-* dependencies is ~25MB



这样做:
<dependency> 
    <groupId>org.springframework.data</groupId> 
    <artifactId>spring-data-jpa</artifactId> 
</dependency> 

In my sample project, the artifact produced without starter-* dependencies is ~15MB



(2)排除自动配置

排除不需要的自动配置:
@Configuration 
@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class}) 
public class MyConfiguration { 
} 

(3)Spring Boot属性

尽可能在application.properties中禁用它(同时确保它也没有负面影响):
spring.main.web-environment=false 
spring.main.banner-mode=off 
spring.jmx.enabled=false 
server.error.whitelabel.enabled=false 
server.jsp-servlet.registered=false 
spring.freemarker.enabled=false 
spring.groovy.template.enabled=false 
spring.http.multipart.enabled=false 
spring.mobile.sitepreference.enabled=false 
spring.session.jdbc.initializer.enabled=false 
spring.thymeleaf.cache=false 
... 

(4)明智地选择嵌入式Web容器

如果使用嵌入式Web容器启动Spring Boot,则可以选择其他容器:
  • tomcat(默认情况下)
  • undertow(https://github.com/spring-projects/spring-boot/tree/master/spring-boot-samples/spring-boot-sample-undertow)
  • jetty (https://github.com/spring-projects/spring-boot/tree/master/spring-boot-samples/spring-boot-sample-jetty)
  • ...

  • (5)Spring的建议
  • 内存:java -Xmx32m -Xss256k -jar target/demo-0.0.1-SNAPSHOT.jar
  • 线程数:server.tomcat.max-threads: 4
  • 来源:spring-boot-memory-performance

  • (6)另请参见:
  • How to reduce Spring memory footprint