столкнулся с проблемой при запуске весенней загрузки с использованием hikaricp

Я сделал то же самое, как предложили некоторые блоги. Но все же я не смог решить проблему.

Окружающая среда:

spring - 4.2.5.RELEASE
spring boot - 1.3.3.RELEASE
hikariCP - 2.4.7

@Bean(name="HikariDataSource",destroyMethod = "shutdown")
    public DataSource dataSource2() {
        HikariConfig config = new HikariConfig();
        config.setDriverClassName("oracle.jdbc.OracleDriver");
        config.setJdbcUrl("");
        config.setUsername("");
        config.setPassword("");
        config.addDataSourceProperty("cachePrepStmts", "true");
        config.addDataSourceProperty("prepStmtCacheSize", "250");
        config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
        config.setPoolName("Hikaripool-1");

        HikariDataSource ds = new HikariDataSource(config);
        return ds;
    }
        @Bean
    public JdbcTemplate getJdbcTemplate() {

        return new JdbcTemplate(dataSource2());
    }

Исключение:

java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: org.springframework.jmx.export.UnableToRegisterMBeanException: Unable to register MBean [HikariDataSource (null)] with key 'dataSource'; nested exception is javax.management.InstanceAlreadyExistsException: com.zaxxer.hikari:name=dataSource,type=HikariDataSource
Caused by: javax.management.InstanceAlreadyExistsException: com.zaxxer.hikari:name=dataSource,type=HikariDataSource

Может ли кто-нибудь помочь мне в решении этой проблемы.


person Yaswanth    schedule 28.08.2016    source источник
comment
Почему вы делаете все это, когда Spring Boot автоматически настраивает Datasource для вас?   -  person Stephane Nicoll    schedule 28.08.2016


Ответы (1)


Ошибка «InstanceAlreadyExistsException: com.zaxxer.hikari:name=dataSource» означает, что для источника данных присутствует еще один экземпляр. Пожалуйста, проверьте вашу конфигурацию. Вот пример кода для jdbcTemplate с использованием HikariCP, Spring Boot 1.4.0 и hsqldb. Пожалуйста, проверьте HikariCPConnTest.java ниже. Надеюсь это поможет.

pom.xml

<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>Spring-HikariCP</groupId>
<artifactId>com.my</artifactId>
<version>0.0.1-SNAPSHOT</version>
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.4.0.RELEASE</version>
    <relativePath />
</parent>
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>
    <dependency>
        <groupId>org.hsqldb</groupId>
        <artifactId>hsqldb</artifactId>
    </dependency>
    <dependency>
        <groupId>com.zaxxer</groupId>
        <artifactId>HikariCP</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
  </dependencies>
</project>

application.properties

spring.datasource.driverClassName=org.hsqldb.jdbc.JDBCDriver
spring.datasource.url=jdbc:hsqldb:mem:testdb
spring.datasource.username=sa
spring.datasource.password=

HikariCPConn.java

import javax.sql.DataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;

@Component
@ConfigurationProperties
public class HikariCPConn {

@Value("${spring.datasource.driverClassName}")
private String driverClassName;

@Value("${spring.datasource.url}")
private String url;

@Value("${spring.datasource.username}")
private String user;

@Value("${spring.datasource.password}")
private String password;

@Bean
public DataSource getDataSource() {
    HikariConfig hikariConfig = new HikariConfig();
    hikariConfig.setUsername(user);
    hikariConfig.setPassword(password);
    hikariConfig.setDriverClassName(driverClassName);
    hikariConfig.setJdbcUrl(url);
    return new HikariDataSource(hikariConfig);
}

@Bean
public JdbcTemplate getJdbcTemplate() {
    return new JdbcTemplate(getDataSource());
   }
}

MySpringBootApp.java

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

@SpringBootApplication
public class MySpringBootApp {
    public static void main(String[] args) {
    SpringApplication.run(new Object[] { MySpringBootApp.class }, args);

   }
}

HikariCPConnTest.java

import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
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.jdbc.core.JdbcTemplate;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = MySpringBootApp.class)
public class HikariCPConnTest {

@Autowired
HikariCPConn hkConn;

@Test
public void testInsert() {
    JdbcTemplate jt = hkConn.getJdbcTemplate();
    jt.execute("create table employee (id int, name varchar(20))");
    jt.execute("insert into employee (id, name) values (1, 'Emp1')");
    jt.execute("insert into employee (id, name) values (2, 'Emp2')");
    List<Map<String, Object>> data = jt.queryForList("select * from employee");
    assertEquals(2,data.size());
    for (Map map : data) {
        System.out.println(map);
       }
   }
}
person abaghel    schedule 28.08.2016