0

我有一个不是 Web 应用程序的 Spring Boot 应用程序。在这个应用程序中,我在以下 bean 的帮助下配置了嵌入式 tomcat。

@Bean public TomcatServletWebServerFactory tomcatFactory() {

    return new TomcatServletWebServerFactory() {

        protected TomcatWebServer getTomcatWebServer(Tomcat tomcat) {
            tomcat.enableNaming();
            return super.getTomcatWebServer(tomcat);
        }

        protected void postProcessContext(Context context) {
            ContextResource contextResource = new ContextResource();
            contextResource.setName("jdbc/BPMDB");
            contextResource.setType(DataSource.class.getName());
            contextResource.setProperty("driverClassName", env.getProperty("bpm.db.driverClassName"));
            contextResource.setProperty("url", env.getProperty("bpm.db.url"));
            contextResource.setProperty("username", env.getProperty("bpm.db.username"));
            contextResource.setProperty("password", env.getProperty("bpm.db.password"));
            context.getNamingResources().addResource(contextResource);
        }
    };

}

我如何为这个嵌入式 tomcat 做连接池。我正在使用 spring boot 2.x,它说 hikaricp 是默认连接池,但是如何将它设置到这个嵌入式 tomcat 中。这是否需要设置诸如 spring.datasource.hikari.initial-size=15 spring.datasource.hikari.max-wait=20000 之类的属性

但是再次启动将如何知道以及我将如何知道使用了这些属性。

谢谢。

4

1 回答 1

0

我的问题得到了答案。

这很简单。我们只需要创建一个 DataSource 引用并自动装配它,并提及数据库相关属性以及 hikari 相关属性。

代码如下。

@Autowired
public DataSource dataSource; 

将上面添加到您的 @Configuration 标记类,并将以下属性添加到 application.properties 文件。

spring.datasource.driver-class=...
spring.datasource.url=jdbc:oracle:thin:....
spring.datasource.username=..
spring.datasource.password=..

spring.datasource.hikari.initial-size=15
spring.datasource.hikari.max-wait=20000
spring.datasource.hikari.max-active=50
spring.datasource.hikari.max-idle=50
spring.datasource.hikari.min-idle=8

我还编写了一个测试用例来检查 hikari 连接池。下面是代码。

import javax.sql.DataSource;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest(
    properties = "spring.datasource.type=com.zaxxer.hikari.HikariDataSource",
    classes = {ApplicationConfiguration.class,PersistenceJpaContext.class}
)
public class HikariConnectionPoolTest {


    @Autowired
    private DataSource dataSource;

    @Test
    public void hikariConnectionPoolIsConfigured() {
        assertEquals("com.zaxxer.hikari.HikariDataSource", dataSource.getClass().getName());
    }
}
于 2019-08-29T11:07:47.293 回答