Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[feat] LineChart API 개선 #485

Merged
merged 3 commits into from
Oct 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package co.fineants.api.domain.gainhistory.domain.entity;

import java.time.format.DateTimeFormatter;

import co.fineants.api.domain.BaseEntity;
import co.fineants.api.domain.common.money.Expression;
import co.fineants.api.domain.common.money.Money;
import co.fineants.api.domain.common.money.MoneyConverter;
import co.fineants.api.domain.portfolio.domain.entity.Portfolio;
Expand Down Expand Up @@ -42,6 +45,8 @@ public class PortfolioGainHistory extends BaseEntity {
@JoinColumn(name = "portfolio_id")
private Portfolio portfolio;

private static final DateTimeFormatter LINE_CHART_KEY_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");

private PortfolioGainHistory(Money totalGain, Money dailyGain, Money cash, Money currentValuation,
Portfolio portfolio) {
this(null, totalGain, dailyGain, cash, currentValuation, portfolio);
Expand All @@ -65,4 +70,17 @@ public static PortfolioGainHistory create(Money totalGain, Money dailyGain, Mone
Portfolio portfolio) {
return new PortfolioGainHistory(totalGain, dailyGain, cash, currentValuation, portfolio);
}

public String getLineChartKey() {
return LINE_CHART_KEY_FORMATTER.format(super.getCreateAt());
}

/**
* Return cash + currentValuation
*
* @return cash + currentValuation
*/
public Expression calculateTotalPortfolioValue() {
return cash.plus(currentValuation);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import java.util.ArrayList;
import java.util.List;

import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

Expand All @@ -26,6 +27,7 @@ public class PortfolioGainHistoryService {
private final CurrentPriceRedisRepository currentPriceRedisRepository;

@Transactional
@CacheEvict(value = "lineChartCache", allEntries = true)
public PortfolioGainHistoryCreateResponse addPortfolioGainHistory() {
List<Portfolio> portfolios = portfolioRepository.findAll();
List<PortfolioGainHistory> portfolioGainHistories = new ArrayList<>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,8 @@ public ApiResponse<List<DashboardPieChartResponse>> readPieChart(
@GetMapping("/lineChart")
public ApiResponse<List<DashboardLineChartResponse>> readLineChart(
@MemberAuthenticationPrincipal MemberAuthentication authentication) {
List<DashboardLineChartResponse> response = dashboardService.getLineChart(authentication.getId());
log.debug("response = {}", response);
return ApiResponse.success(DashboardSuccessCode.OK_LINE_CHART,
dashboardService.getLineChart(authentication.getId()));
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
package co.fineants.api.domain.portfolio.service;

import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
Expand Down Expand Up @@ -114,26 +115,24 @@ public List<DashboardPieChartResponse> getPieChart(Long memberId) {

@Transactional(readOnly = true)
@Secured("ROLE_USER")
@Cacheable(value = "lineChartCache", key = "#memberId")
public List<DashboardLineChartResponse> getLineChart(Long memberId) {
List<Portfolio> portfolios = portfolioRepository.findAllByMemberId(memberId);
if (portfolios.isEmpty()) {
return new ArrayList<>();
}
List<PortfolioGainHistory> portfolioGainHistories = new ArrayList<>();
for (Portfolio portfolio : portfolios) {
portfolioGainHistories.addAll(portfolioGainHistoryRepository.findAllByPortfolioId(portfolio.getId()));
}
Map<String, Expression> timeValueMap = new HashMap<>();
for (PortfolioGainHistory portfolioGainHistory : portfolioGainHistories) {
String time = portfolioGainHistory.getCreateAt().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
timeValueMap.put(time, timeValueMap.getOrDefault(time, Money.zero())
.plus(portfolioGainHistory.getCash())
.plus(portfolioGainHistory.getCurrentValuation()));
}
return timeValueMap.keySet()
List<PortfolioGainHistory> histories = portfolioRepository.findAllByMemberId(memberId).stream()
.map(Portfolio::getId)
.map(portfolioGainHistoryRepository::findAllByPortfolioId)
.flatMap(Collection::stream)
.toList();

Map<String, Expression> result = histories.stream()
.collect(Collectors.toMap(
PortfolioGainHistory::getLineChartKey,
PortfolioGainHistory::calculateTotalPortfolioValue,
Expression::plus
));
return result.keySet()
.stream()
.sorted()
.map(key -> DashboardLineChartResponse.of(key, timeValueMap.get(key)))
.map(key -> DashboardLineChartResponse.of(key, result.get(key)))
.toList();
}
}
18 changes: 17 additions & 1 deletion src/main/java/co/fineants/api/global/config/CacheConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,21 @@
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import com.fasterxml.jackson.databind.ObjectMapper;

import lombok.RequiredArgsConstructor;

@EnableCaching
@Configuration
@RequiredArgsConstructor
public class CacheConfig {

private final ObjectMapper objectMapper;

@Bean
public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
// 기본 캐시 설정 (10분 TTL)
Expand All @@ -27,7 +36,14 @@ public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory)
// 캐시별 만료 시간 설정
Map<String, RedisCacheConfiguration> cacheConfigurations = new HashMap<>();
cacheConfigurations.put("tickerSymbols",
RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofMinutes(5))); // 5분 TTL
RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofMinutes(5))); // 5 minute TTL

RedisSerializationContext.SerializationPair<Object> serializer = RedisSerializationContext.SerializationPair.fromSerializer(
new Jackson2JsonRedisSerializer<>(objectMapper, Object.class));
cacheConfigurations.put("lineChartCache",
RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofHours(24))
.serializeValuesWith(serializer)
); // 24 hourTTL

return RedisCacheManager.builder(redisConnectionFactory)
.cacheDefaults(defaultCacheConfig)
Expand Down