性能优化
1. JVM 调优
1.1 内存配置
bash
java -Xms2g -Xmx4g \
-XX:+UseG1GC \
-XX:MaxGCPauseMillis=200 \
-XX:+HeapDumpOnOutOfMemoryError \
-XX:HeapDumpPath=/logs/heapdump.hprof \
-XX:+PrintGCDetails \
-XX:+PrintGCDateStamps \
-Xloggc:/logs/gc.log \
-jar app.jar1.2 G1GC 配置
bash
java -XX:+UseG1GC \
-XX:InitiatingHeapOccupancyPercent=45 \
-XX:G1HeapRegionSize=16m \
-XX:G1ReservePercent=15 \
-XX:G1NewSizePercent=10 \
-XX:G1MaxNewSizePercent=30 \
-XX:G1MixedGCCountTarget=16 \
-XX:G1HeapWastePercent=5 \
-jar app.jar1.3 虚拟线程
yaml
spring:
threads:
virtual:
enabled: true2. 数据库优化
2.1 连接池配置
yaml
spring:
datasource:
hikari:
maximum-pool-size: 20
minimum-idle: 5
idle-timeout: 300000
connection-timeout: 20000
max-lifetime: 1200000
leak-detection-threshold: 600002.2 JPA 优化
yaml
spring:
jpa:
properties:
hibernate:
jdbc:
batch_size: 50
batch_versioned_data: true
order_inserts: true
order_updates: true
generate_statistics: false
cache:
use_second_level_cache: true
use_query_cache: true
region:
factory_class: org.hibernate.cache.jcache.JCacheRegionFactory2.3 查询优化
java
@Entity
@Table(name = "orders")
@BatchSize(size = 50)
public class Order {
@OneToMany(mappedBy = "order", fetch = FetchType.LAZY)
@BatchSize(size = 50)
private List<OrderItem> items = new ArrayList<>();
}
@Repository
public interface OrderRepository extends JpaRepository<Order, Long> {
@EntityGraph(attributePaths = {"items"})
Optional<Order> findWithItemsById(Long id);
@QueryHints(@QueryHint(name = org.hibernate.annotations.QueryHints.CACHEABLE, value = "true"))
List<Order> findByStatus(OrderStatus status);
}3. 缓存优化
3.1 多级缓存
java
@Configuration
public class CacheConfig {
@Bean
public CacheManager cacheManager(RedisConnectionFactory factory) {
CaffeineCacheManager caffeineManager = new CaffeineCacheManager();
caffeineManager.setCaffeine(Caffeine.newBuilder()
.maximumSize(1000)
.expireAfterWrite(Duration.ofMinutes(5)));
RedisCacheManager redisManager = RedisCacheManager.builder(factory)
.cacheDefaults(RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofMinutes(30)))
.build();
return new CompositeCacheManager(caffeineManager, redisManager);
}
}3.2 缓存策略
java
@Service
public class ProductService {
private final ProductRepository productRepository;
private final RedisTemplate<String, Object> redisTemplate;
private static final String LOCAL_CACHE = "local:product:";
private static final String REDIS_CACHE = "redis:product:";
public Product getProduct(Long id) {
String localKey = LOCAL_CACHE + id;
String redisKey = REDIS_CACHE + id;
Product product = (Product) localCache.get(localKey);
if (product != null) {
return product;
}
product = (Product) redisTemplate.opsForValue().get(redisKey);
if (product != null) {
localCache.put(localKey, product);
return product;
}
product = productRepository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException("商品不存在"));
redisTemplate.opsForValue().set(redisKey, product, Duration.ofMinutes(30));
localCache.put(localKey, product);
return product;
}
}4. 异步处理
4.1 异步任务
java
@Configuration
@EnableAsync
public class AsyncConfig {
@Bean(name = "taskExecutor")
public Executor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(10);
executor.setMaxPoolSize(50);
executor.setQueueCapacity(100);
executor.setThreadNamePrefix("async-");
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
executor.initialize();
return executor;
}
}
@Service
public class NotificationService {
@Async("taskExecutor")
public CompletableFuture<Void> sendNotification(Long userId, String message) {
doSendNotification(userId, message);
return CompletableFuture.completedFuture(null);
}
}4.2 响应式编程
java
@Service
public class ReactiveProductService {
private final ReactiveProductRepository repository;
public Flux<Product> searchProducts(String keyword) {
return repository.findByNameContaining(keyword)
.cache(Duration.ofMinutes(5));
}
public Mono<Product> getProduct(Long id) {
return repository.findById(id)
.switchIfEmpty(Mono.error(new ResourceNotFoundException("商品不存在")));
}
}5. 网络优化
5.1 HTTP 连接池
java
@Configuration
public class HttpClientConfig {
@Bean
public RestTemplate restTemplate() {
HttpComponentsClientHttpRequestFactory factory =
new HttpComponentsClientHttpRequestFactory();
PoolingHttpClientConnectionManager connectionManager =
new PoolingHttpClientConnectionManager();
connectionManager.setMaxTotal(200);
connectionManager.setDefaultMaxPerRoute(50);
CloseableHttpClient httpClient = HttpClientBuilder.create()
.setConnectionManager(connectionManager)
.build();
factory.setHttpClient(httpClient);
factory.setConnectTimeout(5000);
factory.setReadTimeout(10000);
return new RestTemplate(factory);
}
}5.2 Gzip 压缩
yaml
server:
compression:
enabled: true
mime-types: application/json,application/xml,text/html,text/xml,text/plain
min-response-size: 10246. 监控告警
6.1 Prometheus 指标
java
@Configuration
public class MetricsConfig {
@Bean
public MeterRegistryCustomizer<MeterRegistry> metricsCommonTags() {
return registry -> registry.config()
.commonTags("application", "user-service")
.commonTags("env", "prod");
}
}6.2 告警规则
yaml
groups:
- name: spring-boot-alerts
rules:
- alert: HighResponseTime
expr: histogram_quantile(0.95, rate(http_server_requests_seconds_bucket[5m])) > 1
for: 5m
labels:
severity: warning
annotations:
summary: "高响应时间"
- alert: HighErrorRate
expr: rate(http_server_requests_seconds_count{status=~"5.."}[5m]) > 0.1
for: 5m
labels:
severity: critical
annotations:
summary: "高错误率"7. 小结
本章学习了性能优化的核心内容:
| 内容 | 要点 |
|---|---|
| JVM 调优 | 内存配置、GC 配置、虚拟线程 |
| 数据库优化 | 连接池、JPA 配置、查询优化 |
| 缓存优化 | 多级缓存、缓存策略 |
| 异步处理 | @Async、响应式编程 |
| 网络优化 | HTTP 连接池、Gzip 压缩 |
| 监控告警 | Prometheus、告警规则 |
下一章将学习安全最佳实践。