Default configuration of H2 in-memory database set up by Springboot - java

I am using H2 database with Spring Boot (version 2.3.3.RELEASE) with all default settings for H2 database.
Here are the all files of my application.
pom.xml
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.3.RELEASE</version>
<relativePath/>
</parent>
<dependencies>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
application.properties
spring.h2.console.enabled=true
Application.java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import java.sql.SQLException;
#SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
After starting the application when i am trying to connect the H2 database (configured and started by springboot with all default configuration) using below credentials,
I am getting error saying
Database "mem:testDB" not found, either pre-create it or allow remote
database creation
How can I connect to H2 database configured and started by Spring Boot with all the default credentials.
I don't want to override any configuration in application.properties files except spring.h2.console.enabled=true.

In newer version of Spring Boot (2.2+), look for the following log message on your console: Use the JDBC URL to connect on /h2-console page:
Spring Boot 2.2+:
INFO H2ConsoleAutoConfiguration : H2 console available at '/h2-console'. Database available at 'jdbc:h2:mem:testdb'
Spring Boto 2.3+:
INFO H2ConsoleAutoConfiguration : H2 console available at '/h2-console'. Database available at 'jdbc:h2:mem:621dd224-01db-4137-807f-b9c3046de64d'

Only enabling console wouldn't be sufficient, you also need to mention which db you want connect. In your case if you want connect in memory db add below properties as well, then try to connect your in memory db using same creds
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=

Related

spring data,determine whether neo4j has been installed(connectable)

I have a spring data (spring boot and spring cloud) project,and add neo4j starter to it,but in different production environments, I am not sure is neo4j installed.
I use neo4j 3.5,and add dependence:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-neo4j</artifactId>
</dependency>
spring boot is 2.1.8:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.8.RELEASE</version>
<relativePath/>
</parent>
A repository:
public interface UseRepository extends Neo4jRepository<Use, String> {
}
in the application.yml:
spring:
profiles:
active: ${activeProfiles:dev}
data:
neo4j:
uri: bolt://localhost:7687
username: neo4j
password: neo4j
open-in-view: false
Then in a service,I can use the repository:
Iterable<Use> uses = useRepository.findAll();
I can launch the project if no neo4j installed,but if I call any method of any other service with a #Transactional, it will throw a exception Could not open Neo4j Session for transaction,seems the whole project not work.How to make other service class work even neo4j is down?

Connect to MSSQL v18 from Spring boot application using windows authentication

I am currently using the below properties to connect to localhost from Java spring boot application:
spring.jpa.hibernate.ddl-auto=create
spring.datasource.url=jdbc:sqlserver://localhost:1433;database=vlad;integratedSecurity=true
spring.jpa.properties.hibernate.format_sql=true
springdoc.api-docs.path=/api-docs
From Java spring boot this is not working. The error I get is:
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
You will most likely need to configure your Dialect and Include a driver:
application.properties:
spring.datasource.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.jpa.hibernate.dialect=org.hibernate.dialect.SQLServer2016Dialect
You will also most likely need to add driver and auth dependency to your pom.xml
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
</dependency>
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc_auth</artifactId>
<version>10.2.1.x86</version>
<type>dll</type>
</dependency>
If that doesn't do the trick, you might have to manually download the Driver:
https://learn.microsoft.com/en-us/sql/connect/jdbc/download-microsoft-jdbc-driver-for-sql-server?view=sql-server-2017
Hope it helps

'Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.' error in springboot application

I created a springboot application that uses Spring Boot and Apache Camel JDBC Component for inserting a record in postgreSQL. For this purpose I am using the following dependencies:
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-jdbc</artifactId>
<version>${camel.version}</version>
<!-- use the same version as your Camel core version -->
</dependency>
As for the database configuration, I created the following java class with an application.properties file:
Database Configuration java class:
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import org.apache.camel.support.SimpleRegistry;
import org.apache.commons.dbcp2.BasicDataSource;
public class DatabaseConfiguration {
public static SimpleRegistry createDatabaseConfiguration() throws IOException {
Properties properties = new Properties();
properties.load(new FileInputStream("src/main/resources/application.properties"));
BasicDataSource basic = new BasicDataSource();
basic.setDriverClassName(properties.getProperty("PostgresDBClassname"));
basic.setUsername(properties.getProperty("PostgresDBUsername"));
basic.setPassword(properties.getProperty("PostgresDBPassword"));
basic.setUrl(properties.getProperty("PostgresDBUrl"));
SimpleRegistry registry = new SimpleRegistry();
registry.bind("myDataSource", basic);
return registry;
}
}
application.properties file:
PostgresDBUsername = username
PostgresDBPassword = password
PostgresDBClassname = org.postgresql.Driver
PostgresDBUrl = jdbc:postgresql://localhost:5432/postgres
I wrote the router in the following way, noting that I tried to replace dataSource with myDataSource:
#Component
public class InsertRestService extends RouteBuilder {
#Override
public void configure() throws Exception {
rest("/").produces("text/plain")
.get("insert")
.to("direct:hello");
from("direct:hello")
.transform().simple("INSERT INTO person (name, country) VALUES (DANY, LB)")
.to("jdbc:dataSource") //spring boot starter jdbc creates the bean in the registry
.transform().simple("Data inserted in Postgres successfully");
}
}
I got the following error:
Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.
Reason: Failed to determine a suitable driver class
I provided the URL in the application.properties file PostgresDBUrl
Also note that I downloaded the jdbc driver jar file and added it to the module path, after a right click on the package, build path, configure build path
So what can I do to solve this issue?
Thank you!!
I removed the configuration file (DatabaseConfiguration) and replaced the content of the application.properties file with:
spring.datasource.url=jdbc:postgresql://localhost:5432/test
spring.datasource.username=username
spring.datasource.password=password
spring.datasource.platform=postgres
spring.jpa.hibernate.ddl-auto=none
and it worked!
Check your pom.xml file and switch its packaging into war. It worked for me.
<packaging>war</packaging>

Integrate New Relic with Spring Boot using Micrometer

I am trying to integrate a simple Spring Boot Application with New Relic using Micrometer.
Here are the configurations details:-
application.properties
management.endpoints.web.exposure.include=*
management.endpoint.health.show-details=always
management.metrics.export.newrelic.enabled=true
management.metrics.export.newrelic.api-key:MY_API_KEY // Have added the API key here
management.metrics.export.newrelic.account-id: MY_ACCOUNT_ID // Have added the account id here
logging.level.io.micrometer.newrelic=TRACE
pom.xml
<?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>2.5.5</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>springboot.micrometer.demo</groupId>
<artifactId>micrometer-new-relic</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>micrometer-new-relic</name>
<description>Demo project for actuator integration with new relic using micrometer</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</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>io.micrometer</groupId>
<artifactId>micrometer-registry-new-relic</artifactId>
</dependency>
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-registry-prometheus</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</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>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
I was able to integrate Prometheus with this application using micrometer-registry-prometheus dependency. I had set up Prometheus to run in a Docker container in my local system. I used the following set of commands-
docker pull prom/prometheus
docker run -p 9090:9090 -v D:/Workspaces/STS/server_sent_events_blog/micrometer-new-relic/prometheus.yml:/etc/prometheus/prometheus.yml prom/prometheus
prometheus.yml
global:
scrape_interval: 4s
evaluation_interval: 4s
scrape_configs:
- job_name: 'spring_micrometer'
metrics_path: '/actuator/prometheus'
scrape_interval: 5s
static_configs:
- targets: ['my_ip_address:8080']
When I navigated to localhost:9090/targets I can see that Prometheus dashboard shows my application details and that it can scrape data from it. And in the dashboard, I can see my custom metrics as well along with other metrics.
So my question is I want to achieve the same thing using New Relic. I have added the micrometer-registry-new-relic pom dependency. I have shared the application.properties file as well. I can see logs in my console saying it is sending data to New Relic-
2021-10-24 12:42:04.889 DEBUG 2672 --- [trics-publisher] i.m.n.NewRelicInsightsApiClientProvider : successfully sent 58 metrics to New Relic.
Questions:
What are the next steps?
Do I need a local running server of New Relic as I did for Prometheus?
Where can I visualize this data? I have an account in New Relic, I see nothing there
https://discuss.newrelic.com/t/integrate-spring-boot-actuator-with-new-relic/126732
As per the above link, Spring Bootctuator pushes metric as an event type “SpringBootSample”.
With NRQL query we can confirm this-
FROM SpringBootSample SELECT max(value) TIMESERIES 1 minute WHERE metricName = 'jvmMemoryCommitted'
What does the result of this query indicate? Is it a metric related to my application?
Here is the GitHub link to the demo that I have shared here.
I did not find any clear instructions on this, there are some examples out there but that uses Java agent.
Any kind of help will be highly appreciated.
From what I have learned so far.
There are 3 ways to integrate New Relic with a Spring Boot Application-
Using the Java Agent provided by New Relic
Using New Relic's Micrometer Dependency
Micormeter's New Relic Dependency
1. Configuration using Java Agent Provided By New Relic
Download the Java Agent from this URL- https://docs.newrelic.com/docs/release-notes/agent-release-notes/java-release-notes/
Extract it.
Modify the newrelic.yml file inside the extracted folder to inlcude your
license_key:
app_name:
Create a SpringBoot application with some REST endpoints.
Build the application.
Navigate to the root path where you have extracted the newrelic java agent.
Enter this command
java -javagent:<path to your new relic jar>\newrelic.jar -jar <path to your application jar>\<you rapplication jar name>.jar
To view the application metrics-
Log in to your New Relic account.
Go to Explorer Tab.
Click on Services-APM
You can see the name of your application(which you had mentioned in the newrelic.yml file) listed there.
Click on the application name.
The dashboard should look something like this.
Using New Relic's Micrometer Dependency is the preferred way to do it.
2. Configuration using New Relic's Micrometer Dependency
Add this dependency
<dependency>
<groupId>com.newrelic.telemetry</groupId>
<artifactId>micrometer-registry-new-relic</artifactId>
<version>0.7.0</version>
</dependency>
Modify the MicrometerConfig.java class to add your API Key and Application name.
import java.net.InetAddress;
import java.net.UnknownHostException;
import org.springframework.boot.actuate.autoconfigure.metrics.CompositeMeterRegistryAutoConfiguration;
import org.springframework.boot.actuate.autoconfigure.metrics.MetricsAutoConfiguration;
import org.springframework.boot.actuate.autoconfigure.metrics.export.simple.SimpleMetricsExportAutoConfiguration;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.newrelic.telemetry.Attributes;
import com.newrelic.telemetry.micrometer.NewRelicRegistry;
import com.newrelic.telemetry.micrometer.NewRelicRegistryConfig;
import java.time.Duration;
import io.micrometer.core.instrument.config.MeterFilter;
import io.micrometer.core.instrument.util.NamedThreadFactory;
#Configuration
#AutoConfigureBefore({ CompositeMeterRegistryAutoConfiguration.class, SimpleMetricsExportAutoConfiguration.class })
#AutoConfigureAfter(MetricsAutoConfiguration.class)
#ConditionalOnClass(NewRelicRegistry.class)
public class MicrometerConfig {
#Bean
public NewRelicRegistryConfig newRelicConfig() {
return new NewRelicRegistryConfig() {
#Override
public String get(String key) {
return null;
}
#Override
public String apiKey() {
return "your_api_key"; // for production purposes take it from config file
}
#Override
public Duration step() {
return Duration.ofSeconds(5);
}
#Override
public String serviceName() {
return "your_service_name"; // take it from config file
}
};
}
#Bean
public NewRelicRegistry newRelicMeterRegistry(NewRelicRegistryConfig config) throws UnknownHostException {
NewRelicRegistry newRelicRegistry = NewRelicRegistry.builder(config)
.commonAttributes(new Attributes().put("host", InetAddress.getLocalHost().getHostName())).build();
newRelicRegistry.config().meterFilter(MeterFilter.ignoreTags("plz_ignore_me"));
newRelicRegistry.config().meterFilter(MeterFilter.denyNameStartsWith("jvm.threads"));
newRelicRegistry.start(new NamedThreadFactory("newrelic.micrometer.registry"));
return newRelicRegistry;
}
}
Run the application.
To view the Application metrics-
Log in to your New Relic account.
Go to Explorer Tab.
Click on Services-OpenTelemetry
You can see the name of your application(which you had mentioned in the MicrometerConfig file) listed there.
Click on the application name.
The dashboard should look something like this.
What are the next steps?
It seems you are done and successfully shipped metrics to NewRelic.
Do I need a local running server of New Relic as I did for Prometheus?
No, NewRelic is a SaaS offering.
Where can I visualize this data? I have an account in New Relic, I see nothing there
It seems you already found it (screenshot).
What does the result of this query indicate? Is it a metric related to my application?
From the screenshot, I can't tell if it is your application but this seems to be the jvm.memory.committed metric pushed by a Spring Boot app (so likely).
In order to see if this is your app or not, you can add common tags which can tell the name of the app and some kind of an instance ID (or hostname?) in case you have multiple instances from the same app, see:
Spring Boot Docs (I would do this)
Micrometer Docs (do this if you don't use Spring Boot or want to do something tricky)
Real-World Example

Spring boot default connection pool tomcat properties not working

We are using spring boot 1.5.9.RELEASE. We have spring-boot-starter-data-jpa and mysql-connector-java in our maven dependency to connect to MySQL db. We have not configured any connection pool. According to the documentation since we are using spring-boot-starter-data-jpa tomcat connection pool is used as default connection pool. But when we try setting connection pool properties as spring.datasource.tomcat.* it is not working. But the same is working when spring.datasource.* format is used.
i.e spring.datasource.max-active=50 is working where as spring.datasource.tomcat.max-active=50 is not working. I confirmed this by printing Datasource in main class for which I'm getting org.apache.tomcat.jdbc.pool.DataSource#<objecthash>{key1=value1; key2=value2; ....} as output.
Why is this happening? Is it because we are using mysql-connector-java it's not reading tomcat connection pool properties? if that's the case then when I print Datasource how am I getting org.apache.tomcat.jdbc.pool.DataSource#a1f72f5 as data source with configured values? Or did I miss out something from the documentation? or JPA is not working properly?
pom.xml:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
<relativePath />
</parent>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
</dependencies>
Mainclass.java
import javax.sql.DataSource;
#SpringBootApplication
public class MainClass implements CommandLineRunner {
#Autowired
DataSource dataSource;
public static void main(String[] args) {
SpringApplication.run(MainClassChild.class, args);
}
#Override
public void run(String... args) throws Exception {
System.out.println("DATASOURCE = " + dataSource);
}
}
Application.properties
spring.datasource.url=jdbc:mysql://1.2.3.4/dbname?useSSL=false
spring.datasource.username=username
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#Working
spring.datasource.max-active=30
spring.datasource.max-idle=20
spring.datasource.min-idle=10
#Not Working
spring.datasource.tomcat.max-active=30
spring.datasource.tomcat.max-idle=20
spring.datasource.tomcat.min-idle=10
Note: We autowire jdbctemplate and use it in DAO.

Categories

Resources