-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathCachedCartService.java
More file actions
39 lines (31 loc) · 1.16 KB
/
CachedCartService.java
File metadata and controls
39 lines (31 loc) · 1.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package com.ecommerce.service;
import com.ecommerce.model.Product;
import com.ecommerce.repository.ProductRepository;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.util.List;
@Service
public class CachedCartService {
private final ProductRepository productRepository;
public CachedCartService(ProductRepository productRepository) {
this.productRepository = productRepository;
}
@Cacheable(value = "productPrices", key = "#productId")
public BigDecimal getProductPrice(Long productId) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
Product product = productRepository.findById(productId).orElse(null);
return product != null ? product.getPrice() : BigDecimal.ZERO;
}
public BigDecimal calculateBulkCartTotal(List<Long> productIds) {
BigDecimal total = BigDecimal.ZERO;
for (Long productId : productIds) {
total = total.add(getProductPrice(productId));
}
return total;
}
}