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

Bael 8958: Introduction to New Relic for Java #18189

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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
1 change: 1 addition & 0 deletions libraries-apm/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
## Relevant Articles
596 changes: 596 additions & 0 deletions libraries-apm/new-relic/currency-converter/newrelic/newrelic.yml

Large diffs are not rendered by default.

78 changes: 78 additions & 0 deletions libraries-apm/new-relic/currency-converter/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.4.1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.baeldung</groupId>
<artifactId>currency-converter</artifactId>
<version>0.0.1</version>
<name>Currency Converter</name>
<description>Currency Converter Demo</description>

<properties>
<java.version>21</java.version>
<maven.compiler.source>21</maven.compiler.source>
<maven.compiler.target>21</maven.compiler.target>
</properties>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.12.0</version>
</dependency>

<dependency>
<groupId>com.newrelic.agent.java</groupId>
<artifactId>newrelic-java</artifactId>
<version>8.17.0</version>
<scope>provided</scope>
<type>zip</type>
</dependency>

<dependency>
<groupId>com.newrelic.agent.java</groupId>
<artifactId>newrelic-api</artifactId>
<version>8.17.0</version>
</dependency>
</dependencies>

</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package com.baeldung.currency_converter;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class CurrencyConverterApplication {

public static void main(String[] args) {
SpringApplication.run(CurrencyConverterApplication.class, args);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package com.baeldung.currency_converter.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

@Configuration
public class AppConfig {
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package com.baeldung.currency_converter.config;

import java.time.Duration;

import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericToStringSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
@EnableCaching
public class RedisConfig {
@Bean
public RedisCacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
RedisCacheConfiguration cacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofSeconds(90));

return RedisCacheManager.builder(redisConnectionFactory)
.cacheDefaults(cacheConfiguration)
.build();
}

@Bean
public RedisTemplate<String, Double> redisTemplate(RedisConnectionFactory connectionFactory) {
RedisTemplate<String, Double> template = new RedisTemplate<>();
template.setConnectionFactory(connectionFactory);
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new GenericToStringSerializer<>(Double.class));
return template;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package com.baeldung.currency_converter.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baeldung.currency_converter.service.CurrencyConverterService;

@RestController
@RequestMapping("/api/currency")
public class CurrencyConverterController {
private final CurrencyConverterService currencyConverterService;

public CurrencyConverterController(CurrencyConverterService currencyConverterService) {
this.currencyConverterService = currencyConverterService;
}

@GetMapping("/convert")
public double convertCurrency(@RequestParam String targetCurrency,
@RequestParam double amount) {
return currencyConverterService.getConvertedAmount(targetCurrency, amount);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
package com.baeldung.currency_converter.dto;

import java.util.Map;

public class ExchangeRateResponse {
private String disclaimer;
private String license;
private Long timestamp;
private String base;
private Map<String, Double> rates;

public String getDisclaimer() {
return disclaimer;
}

public void setDisclaimer(String disclaimer) {
this.disclaimer = disclaimer;
}

public String getLicense() {
return license;
}

public void setLicense(String license) {
this.license = license;
}

public Long getTimestamp() {
return timestamp;
}

public void setTimestamp(Long timestamp) {
this.timestamp = timestamp;
}

public String getBase() {
return base;
}

public void setBase(String base) {
this.base = base;
}

public Map<String, Double> getRates() {
return rates;
}

public void setRates(Map<String, Double> rates) {
this.rates = rates;
}

@Override
public String toString() {
return "ExchangeRateResponse{" +
"disclaimer='" + disclaimer + '\'' +
", license='" + license + '\'' +
", timestamp=" + timestamp +
", base='" + base + '\'' +
", rates=" + rates +
'}';
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
package com.baeldung.currency_converter.service;

import org.springframework.stereotype.Service;
import com.baeldung.currency_converter.dto.ExchangeRateResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.newrelic.api.agent.NewRelic;
import com.newrelic.api.agent.Trace;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Value;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import java.time.Duration;

@Service
public class CurrencyConverterService {
private static final Logger logger = LoggerFactory.getLogger(CurrencyConverterService.class);

@Value("${openexchangerates.url}")
private String openApiUrl;

@Value("${openexchangerates.app_id}")
private String openApiAppId;

@Value("${openexchangerates.base_currency}")
public String baseCurrency;

private final OkHttpClient client;
private final ObjectMapper objectMapper;
private final RedisTemplate<String, Double> redisTemplate;

public CurrencyConverterService(RedisTemplate<String, Double> redisTemplate) {
this.client = new OkHttpClient();
this.objectMapper = new ObjectMapper();
this.redisTemplate = redisTemplate;
}

@Trace(metricName="CurrencyConversionCalc")
public double getConvertedAmount(String targetCurrency, double amount) {
String cacheKey = baseCurrency + "-" + targetCurrency;

// Try to get rate from cache first
Double cachedRate = redisTemplate.opsForValue().get(cacheKey);
if (cachedRate != null) {
logger.info("Cache hit for key: {}", cacheKey);
return amount * cachedRate;
} else {
logger.info("Cache miss for key: {}, fetching from API", cacheKey);
NewRelic.incrementCounter("Custom/CacheMisses");
}

// Original API call logic
String url = String.format("%s/latest.json?app_id=%s", openApiUrl, openApiAppId);
logger.info("Fetching exchange rates from {}", url);

try {
Request request = new Request.Builder()
.url(url)
.build();

long startTime = System.nanoTime();

try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) {
throw new RuntimeException("Unexpected response code: " + response);
}

long durationInMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime);
NewRelic.addCustomParameter("RatesAPI/ResponseTime", durationInMillis);


String rawResponse = response.body().string();
ExchangeRateResponse exchangeResponse = objectMapper.readValue(rawResponse, ExchangeRateResponse.class);

logger.info("Response headers:");
response.headers().toMultimap().forEach((k, v) -> logger.info("{}: {}", k, v));

String eTagHeaderField = response.header("ETag");
logger.info(eTagHeaderField);

NewRelic.addCustomParameter(cacheKey, eTagHeaderField);

if (exchangeResponse != null && exchangeResponse.getRates() != null) {
Map<String, Double> rates = exchangeResponse.getRates();
Double targetRate = rates.get(targetCurrency);

if (targetRate == null) {
logger.error("Target currency {} not found in rates", targetCurrency);
throw new IllegalArgumentException("Target currency not found in rates.");
}

// Cache the rate before returning
redisTemplate.opsForValue().set(cacheKey, targetRate, Duration.ofHours(24));
logger.info("Cached exchange rate for key: {}", cacheKey);

return amount * targetRate;
}

logger.error("Failed to get exchange rate response");
throw new RuntimeException("Could not retrieve exchange rate.");
}
} catch (Exception e) {
logger.error("Error converting currency: {}", e.getMessage(), e);
NewRelic.noticeError(e);
throw new RuntimeException("Error converting currency", e);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
spring.application.name=Currency Converter

# Redis Configuration
spring.redis.host=localhost
spring.redis.port=6379
# spring.redis.password=
spring.redis.timeout=2000

# Cache Configuration
spring.cache.type=redis

# Open Exchange Rates API Configuration
openexchangerates.url=https://openexchangerates.org
openexchangerates.app_id=<APPLICATION_ID>
openexchangerates.base_currency=USD
21 changes: 21 additions & 0 deletions libraries-apm/new-relic/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung.new-relic</groupId>
<artifactId>new-relic</artifactId>
<packaging>pom</packaging>
<name>new-relic</name>

<parent>
<groupId>com.baeldung</groupId>
<artifactId>libraries-apm</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>

<modules>
<module>currency-converter</module>
</modules>

</project>
Loading