使用Spring Boot时,HikariCP是否需要不同的配置?

时间:2016-08-01 20:27:03

标签: java spring database-connection hikaricp

当我使用HikariCP 2.4.7时,我通常会将其初始化为:

hikariDataSource = new HikariDataSource();
hikariDataSource.setDriverClassName("org.postgresql.Driver");
hikariDataSource.setUsername(DATABASE_USER_NAME);
hikariDataSource.setPassword(DATABASE_PASSWORD);
hikariDataSource.setJdbcUrl(DATABASE_URL);

当我需要连接时:

 try(java.sql.Connection conn = hikariDataSource.getConnection()) {
            Record1 record1 = DSL.using(conn).select(SENSOR.ID)
                    .from(SENSOR)
                    .where(SENSOR.ID.equal(1))
                    .limit(1)
                    .fetchOne();
            System.out.println(record1.getValue(0).toString());
        } catch (SQLException e) {
            e.printStackTrace();
        }

在使用HikariCP和Spring Boot 1.4.0时,我应该以其他方式做某事还是添加一些内容?

更新1:

的build.gradle

compile("org.springframework.boot:spring-boot-starter-web:1.4.0.RELEASE")
compile group: 'org.springframework.boot', name: 'spring-boot-starter-data-jpa', version: '1.4.0.RELEASE'
compile group: 'org.springframework.boot', name: 'spring-boot-starter-jdbc', version: '1.4.0.RELEASE'
compile group: 'com.zaxxer', name: 'HikariCP', version: '2.4.7'

application.properties

server.port=80
spring.datasource.hikari.jdbc-url=jdbc:postgresql://someaddress.com:5432/mydb
spring.datasource.hikari.username=myservice_backend
spring.datasource.hikari.password=mypass
spring.datasource.hikari.driver-class-name=org.postgresql.Driver

但是,在application.properties中添加spring-boot-starter-data-jpaspring-boot-starter-jdbc以及配置后,我得到:

Connected to the target VM, address: '127.0.0.1:53695', transport: 'socket'

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.4.0.RELEASE)

2016-08-03 16:09:34.033  INFO 3492 --- [           main] pl.mypackage.Main                            : Starting Main on Defozo-laptop with PID 3492 (C:\Users\Defozo\IdeaProjects\myProject\build\classes\main started by Defozo in C:\Users\Defozo\IdeaProjects\myProject)
2016-08-03 16:09:34.038  INFO 3492 --- [           main] pl.mypackage.Main                            : No active profile set, falling back to default profiles: default
2016-08-03 16:09:34.091  INFO 3492 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@f58853c: startup date [Wed Aug 03 16:09:34 CEST 2016]; root of context hierarchy
2016-08-03 16:09:35.298  INFO 3492 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Overriding bean definition for bean 'dataSource' with a different definition: replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.jdbc.DataSourceConfiguration$Hikari; factoryMethodName=dataSource; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class]] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.jdbc.DataSourceConfiguration$Tomcat; factoryMethodName=dataSource; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Tomcat.class]]
2016-08-03 16:09:35.820  INFO 3492 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [class org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$b802c57c] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2016-08-03 16:09:36.484  INFO 3492 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 80 (http)
2016-08-03 16:09:36.501  INFO 3492 --- [           main] o.apache.catalina.core.StandardService   : Starting service Tomcat
2016-08-03 16:09:36.503  INFO 3492 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.4
2016-08-03 16:09:36.635  INFO 3492 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2016-08-03 16:09:36.635  INFO 3492 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 2544 ms
2016-08-03 16:09:36.811  INFO 3492 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Mapping servlet: 'dispatcherServlet' to [/]
2016-08-03 16:09:36.814  INFO 3492 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
2016-08-03 16:09:36.815  INFO 3492 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2016-08-03 16:09:36.815  INFO 3492 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2016-08-03 16:09:36.815  INFO 3492 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
2016-08-03 16:09:36.863  WARN 3492 --- [           main] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration': Unsatisfied dependency expressed through constructor parameter 0: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Tomcat.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.apache.tomcat.jdbc.pool.DataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath. If you have database settings to be loaded from a particular profile you may need to active it (no profiles are currently active).; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Tomcat.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.apache.tomcat.jdbc.pool.DataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath. If you have database settings to be loaded from a particular profile you may need to active it (no profiles are currently active).
2016-08-03 16:09:36.874  INFO 3492 --- [           main] o.apache.catalina.core.StandardService   : Stopping service Tomcat
2016-08-03 16:09:36.888  INFO 3492 --- [           main] utoConfigurationReportLoggingInitializer : 

Error starting ApplicationContext. To display the auto-configuration report enable debug logging (start with --debug)


2016-08-03 16:09:36.896 ERROR 3492 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   : 

***************************
APPLICATION FAILED TO START
***************************

Description:

Cannot determine embedded database driver class for database type NONE

Action:

If you want an embedded database please put a supported one on the classpath. If you have database settings to be loaded from a particular profile you may need to active it (no profiles are currently active).

Disconnected from the target VM, address: '127.0.0.1:53695', transport: 'socket'

Process finished with exit code 1

我试图改变这个:

@SpringBootApplication
@EnableAutoConfiguration
public class Main extends SpringBootServletInitializer {

到此:

@SpringBootApplication
@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
public class Main extends SpringBootServletInitializer {

但我仍然得到相同的输出。

更新2:

application.properties

server.port=80
spring.datasource.url=jdbc:postgresql://someaddress.com:5432/mydb
spring.datasource.username=myservice_backend
spring.datasource.password=mypass
spring.datasource.driver-class-name=org.postgresql.Driver

控制台输出:

Connected to the target VM, address: '127.0.0.1:50640', transport: 'socket'

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.4.0.RELEASE)

2016-08-04 12:55:49.369  INFO 11728 --- [           main] pl.mypackage.Main                            : Starting Main on Defozo-laptop with PID 11728 (C:\Users\Defozo\IdeaProjects\AirlyMap3\build\classes\main started by Defozo in C:\Users\Defozo\IdeaProjects\AirlyMap3)
2016-08-04 12:55:49.369  INFO 11728 --- [           main] pl.mypackage.Main                            : No active profile set, falling back to default profiles: default
2016-08-04 12:55:49.432  INFO 11728 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@f58853c: startup date [Thu Aug 04 12:55:49 CEST 2016]; root of context hierarchy
2016-08-04 12:55:50.786  INFO 11728 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Overriding bean definition for bean 'dataSource' with a different definition: replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.jdbc.DataSourceConfiguration$Hikari; factoryMethodName=dataSource; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class]] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.jdbc.DataSourceConfiguration$Tomcat; factoryMethodName=dataSource; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Tomcat.class]]
2016-08-04 12:55:51.304  INFO 11728 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [class org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$932c4431] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2016-08-04 12:55:51.951  INFO 11728 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 80 (http)
2016-08-04 12:55:51.967  INFO 11728 --- [           main] o.apache.catalina.core.StandardService   : Starting service Tomcat
2016-08-04 12:55:51.969  INFO 11728 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.4
2016-08-04 12:55:52.114  INFO 11728 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2016-08-04 12:55:52.114  INFO 11728 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 2682 ms
2016-08-04 12:55:52.315  INFO 11728 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Mapping servlet: 'dispatcherServlet' to [/]
2016-08-04 12:55:52.317  INFO 11728 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
2016-08-04 12:55:52.317  INFO 11728 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2016-08-04 12:55:52.317  INFO 11728 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2016-08-04 12:55:52.317  INFO 11728 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
2016-08-04 12:55:55.402  INFO 11728 --- [           main] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default'
2016-08-04 12:55:55.418  INFO 11728 --- [           main] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [
    name: default
    ...]
2016-08-04 12:55:55.511  INFO 11728 --- [           main] org.hibernate.Version                    : HHH000412: Hibernate Core {5.0.9.Final}
2016-08-04 12:55:55.511  INFO 11728 --- [           main] org.hibernate.cfg.Environment            : HHH000206: hibernate.properties not found
2016-08-04 12:55:55.511  INFO 11728 --- [           main] org.hibernate.cfg.Environment            : HHH000021: Bytecode provider name : javassist
2016-08-04 12:55:55.558  INFO 11728 --- [           main] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
2016-08-04 12:55:56.751  INFO 11728 --- [           main] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.PostgreSQL94Dialect
2016-08-04 12:56:48.037  INFO 11728 --- [           main] o.h.e.j.e.i.LobCreatorBuilderImpl        : HHH000424: Disabling contextual LOB creation as createClob() method threw error : java.lang.reflect.InvocationTargetException
2016-08-04 12:56:48.044  INFO 11728 --- [           main] org.hibernate.type.BasicTypeRegistry     : HHH000270: Type registration [java.util.UUID] overrides previous : org.hibernate.type.UUIDBinaryType@6568f998
2016-08-04 12:56:48.738  INFO 11728 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@f58853c: startup date [Thu Aug 04 12:55:49 CEST 2016]; root of context hierarchy
2016-08-04 12:56:48.890  INFO 11728 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/v1/measurement],methods=[POST]}" onto void pl.mypackage.ResponseGenerator.sendMeasurementFromSensorToDatabase(java.util.Map<java.lang.String, java.lang.String>)
2016-08-04 12:56:48.891  INFO 11728 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/v1/measurements],methods=[GET],produces=[application/json || text/html]}" onto static org.springframework.http.ResponseEntity<java.lang.String> pl.mypackage.ResponseGenerator.getResponseAdequateToRequest(java.util.Map<java.lang.String, java.lang.String>)
2016-08-04 12:56:48.895  INFO 11728 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2016-08-04 12:56:48.895  INFO 11728 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2016-08-04 12:56:48.924  INFO 11728 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2016-08-04 12:56:48.924  INFO 11728 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2016-08-04 12:56:48.988  INFO 11728 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2016-08-04 12:56:49.735  INFO 11728 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2016-08-04 12:56:49.795  INFO 11728 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 80 (http)
2016-08-04 12:56:49.800  INFO 11728 --- [           main] pl.mypackage.Main                            : Started Main in 60.881 seconds (JVM running for 61.327)

它开始了,但它花了大约61秒才开始。为什么这么久?

0 个答案:

没有答案