本内容是NewRelic与springboot进行整合的一个简单入门案例。
plugins {
id 'org.springframework.boot' version '2.2.8.RELEASE'
id 'io.spring.dependency-management' version '1.0.9.RELEASE'
id 'java'
id "de.undercouch.download" version "3.4.3"
}
group = 'com.yuji'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'
repositories {
mavenCentral()
}
task downloadNewrelic(type: Download) {
mkdir 'newrelic'
src 'https://download.newrelic.com/newrelic/java-agent/newrelic-agent/current/newrelic-java.zip'
dest file('newrelic')
}
task unzipNewrelic(type: Copy) {
from zipTree(file('newrelic/newrelic-java.zip'))
into rootDir
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter'
compile group: 'org.springframework.boot', name: 'spring-boot-starter-web'
compile group: 'com.newrelic.agent.java', name: 'newrelic-agent', version: '5.13.0'
compile group: 'com.newrelic.agent.java', name: 'newrelic-api', version: '5.13.0'
testImplementation('org.springframework.boot:spring-boot-starter-test') {
exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
}
}
test {
useJUnitPlatform()
}
./gradlew downloadNewrelic
./gradlew unzipNewrelic
java -javaagent:newrelic/newrelic.jar -jar build/libs/yourapp-0.0.1-SNAPSHOT.jar
此时登录https://newrelic.com网站尝试是否可以搜索该应用,则整合完成。
对于mac系统:
-Dnewrelic.config.file=yourpath/newrelic.yml
-javaagent:yourpath/newrelic.jar
对于win系统:
-javaagent:yourpath/newrelic/newrelic.jar
如果报错,就将上一句也加进去。此时点击run,会发现同样newrelic.jar也正确加载了。
package com.yuji.controller;
import java.util.Random;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.newrelic.api.agent.NewRelic;
import com.newrelic.api.agent.Trace;
@RestController
public class Rest {
@GetMapping("/hello")
@Trace(dispatcher = true)
public String hello() {
NewRelic.setTransactionName(null, "/store");
String userId = "张三";
NewRelic.setUserName(userId);
NewRelic.addCustomParameter("userId", userId);
NewRelic.incrementCounter("Custom/Promotion");
try {
long millisToSleep = new Random().nextInt(5000);
Thread.sleep(millisToSleep);
NewRelic.recordResponseTimeMetric("Custom/RandomSleep", millisToSleep);
} catch (InterruptedException e) {
NewRelic.noticeError(e, false);
}
return "NewRelic API example servlet";
}
}