@Service
@RequiredArgsConstructor
public class CurrencyService {
private final Map<String, CacheEntry> map = new ConcurrentHashMap<>();
private final RestTemplate restTemplate;
 
public BigDecimal getRate(String currency) {
return map.compute(currency, (k, entry) -> {
if (entry == null || !entry.expiresAt().isAfter(Instant.now())) {
response = restTemplate.getForObject(
"https://api.example.com/rates/" + currency,
CurrencyResponse.class
);
return new CacheEntry(response.rate(), Instant.now().plus(Duration.ofMinutes(10)));
}
).rate();
}
}
 
public record CacheEntry(BigDecimal rate, Instant expiresAt) {}