HikariCP连接错误 [英] HikariCP connection error

查看:152
本文介绍了HikariCP连接错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将HikariCP与mariaDB数据库一起使用,但是在我尝试初始化时遇到下一个错误.

Im trying to use HikariCP with a mariaDB database but i getting the next error when im trying to initialize.

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
at com.zaxxer.hikari.pool.HikariPool.initializeConnections(HikariPool.java:581) ~[Dubilets-1.0-SNAPSHOT.jar:?]
at com.zaxxer.hikari.pool.HikariPool.<init>(HikariPool.java:152) ~[Dubilets-1.0-SNAPSHOT.jar:?]
at com.zaxxer.hikari.HikariDataSource.<init>(HikariDataSource.java:73) ~[Dubilets-1.0-SNAPSHOT.jar:?]
at eu.elraro.dubilets.storage.Database.<init>(Database.java:69) [Dubilets-1.0-SNAPSHOT.jar:?]
at eu.elraro.dubilets.storage.MariaDBDatabase.<init>(MariaDBDatabase.java:18) [Dubilets-1.0-SNAPSHOT.jar:?]
at eu.elraro.dubilets.Dubilets.realizaConexion(Dubilets.java:168) [Dubilets-1.0-SNAPSHOT.jar:?]
at eu.elraro.dubilets.Dubilets.inicializaVariables(Dubilets.java:164) [Dubilets-1.0-SNAPSHOT.jar:?]
at eu.elraro.dubilets.Dubilets.onEnable(Dubilets.java:69) [Dubilets-1.0-SNAPSHOT.jar:?]
at org.bukkit.plugin.java.JavaPlugin.setEnabled(JavaPlugin.java:321) [spigot-1.8.8-R0.1-SNAPSHOT-latest.jar:git-Spigot-fdc1440-53fac9f]
at org.bukkit.plugin.java.JavaPluginLoader.enablePlugin(JavaPluginLoader.java:340) [spigot-1.8.8-R0.1-SNAPSHOT-latest.jar:git-Spigot-fdc1440-53fac9f]
at org.bukkit.plugin.SimplePluginManager.enablePlugin(SimplePluginManager.java:405) [spigot-1.8.8-R0.1-SNAPSHOT-latest.jar:git-Spigot-fdc1440-53fac9f]
at org.bukkit.craftbukkit.v1_8_R3.CraftServer.loadPlugin(CraftServer.java:357) [spigot-1.8.8-R0.1-SNAPSHOT-latest.jar:git-Spigot-fdc1440-53fac9f]
at org.bukkit.craftbukkit.v1_8_R3.CraftServer.enablePlugins(CraftServer.java:317) [spigot-1.8.8-R0.1-SNAPSHOT-latest.jar:git-Spigot-fdc1440-53fac9f]
at net.minecraft.server.v1_8_R3.MinecraftServer.s(MinecraftServer.java:414) [spigot-1.8.8-R0.1-SNAPSHOT-latest.jar:git-Spigot-fdc1440-53fac9f]
at net.minecraft.server.v1_8_R3.MinecraftServer.k(MinecraftServer.java:378) [spigot-1.8.8-R0.1-SNAPSHOT-latest.jar:git-Spigot-fdc1440-53fac9f]
at net.minecraft.server.v1_8_R3.MinecraftServer.a(MinecraftServer.java:333) [spigot-1.8.8-R0.1-SNAPSHOT-latest.jar:git-Spigot-fdc1440-53fac9f]
at net.minecraft.server.v1_8_R3.DedicatedServer.init(DedicatedServer.java:263) [spigot-1.8.8-R0.1-SNAPSHOT-latest.jar:git-Spigot-fdc1440-53fac9f]
at net.minecraft.server.v1_8_R3.MinecraftServer.run(MinecraftServer.java:524) [spigot-1.8.8-R0.1-SNAPSHOT-latest.jar:git-Spigot-fdc1440-53fac9f]
at java.lang.Thread.run(Thread.java:745) [?:1.8.0_66]

原因:com.mysql.jdbc.exceptions.jdbc4.CommunicationsException:通信链接失败

我的MariaDBDatabase类:

My MariaDBDatabase class:

public class MariaDBDatabase extends Database {

/*
 * Construct a MySQL database instance.
 *
 * @param host     Host/IP of the MySQL database.
 * @param port     Port of the MySQL database.
 * @param database Database wanted to be access.
 * @param username Username to be authenticated with.
 * @param password Password for the user authentication.
 * @param plugin   Plugin for the schedulers to be assigned to.
 */
public MariaDBDatabase(String host, int port, String database, String username, String password, JavaPlugin plugin) {
    super("org.mariadb.jdbc.MySQLDataSource", "jdbc:mysql://" + host + ":" + port + "/" + database, username, password, plugin);
}

我的数据库类:

public abstract class Database {

private String           jdbcURL;
private HikariDataSource dataSource;
private JavaPlugin       plugin;

/**
 * Construct a database instance.
 *
 * @param className The class name used to get the driver.
 * @param jdbcURL   A JDBC url to use for connecting.
 * @param username  Username to connect with.
 * @param password  Password to authenticate username.
 * @param plugin    A plugin instance for the schedulers to be assigned to.
 */
public Database(String className, String jdbcURL, String username, String password, JavaPlugin plugin) {
    this.jdbcURL = jdbcURL;
    this.plugin = plugin;

    try {
        Bukkit.getLogger().log(Level.INFO, "Initializing the connection pool ... ");
        Class.forName(className);
    } catch (ClassNotFoundException e) {
        Bukkit.getLogger().log(Level.SEVERE, "Exception when trying to initialize the connection pool",e);
        return;
    }

    HikariConfig config = new HikariConfig();

    config.setDriverClassName(className);
    config.setJdbcUrl(jdbcURL);

    config.setUsername(username);
    config.setPassword(password);

    //config.setLeakDetectionThreshold(10000);
    //config.setMaximumPoolSize(10);

    config.setMaximumPoolSize(5);
    config.setConnectionTestQuery("SELECT 1");
    config.setPoolName("HikariCP");

    try {
        dataSource = new HikariDataSource(config);
        Bukkit.getLogger().log(Level.INFO, "Connection pool initialized successfully.");
    } catch (Exception e) {
        Bukkit.getLogger().log(Level.SEVERE, "Exception when trying to initialize the connection pool",e);
    }
}

/**
 * Connects the data pool to the database.
 */
public boolean connect() {
    return isConnected();
}

/**
 * Disconnects (shutdown) the data pool and all connections.
 */
public void disconnect() {
    dataSource.shutdown();
}

/**
 * Query the database and return a cached result.
 *
 * @param query The statement to be queried.
 * @return      Cached rowset returned from query.
 */
public CachedRowSet query(final PreparedStatement preparedStatement) {
    CachedRowSet rowSet = null;

    if (isConnected()) {
        try {
            ExecutorService exe = Executors.newCachedThreadPool();

            Future<CachedRowSet> future = exe.submit(new Callable<CachedRowSet>() {
                public CachedRowSet call() {
                    try {
                        ResultSet resultSet = preparedStatement.executeQuery();

                        CachedRowSet cachedRowSet = new CachedRowSetImpl();
                        cachedRowSet.populate(resultSet);
                        resultSet.close();

                        preparedStatement.getConnection().close();

                        if (cachedRowSet.next()) {
                            return cachedRowSet;
                        }
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }

                    return null;
                }
            });

            if (future.get() != null) {
                rowSet = future.get();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }

    return rowSet;
}

/**
 * Execute a query
 *
 * @param preparedStatement query to be executed.
 */
public void execute(final PreparedStatement preparedStatement) {
    if (isConnected()) {
        Bukkit.getScheduler().runTaskAsynchronously(plugin, new Runnable() {
            public void run() {
                try {
                    preparedStatement.execute();

                    preparedStatement.getConnection().close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}

/**
 * Prepare a statement
 *
 * @param query Query to be prepared.
 * @param vars  Variables to be replaced from ?.
 * @return      a prepared statement.
 */
public PreparedStatement prepareStatement(String query, Object... vars) {
    try {
        PreparedStatement preparedStatement = getConnection().prepareStatement(query);

        int x = 0;

        if (query.contains("?") && vars.length != 0) {
            for (Object var : vars) {
                x++;
                if (var instanceof String) {
                    preparedStatement.setString(x, (String) var);
                } else {
                    preparedStatement.setInt(x, (Integer) var);
                }
            }
        }

        return preparedStatement;
    } catch (SQLException e) {
        e.printStackTrace();
    }

    return null;
}

/**
 * Get a connection from the data pool
 *
 * @return a connection.
 */
public Connection getConnection() {
    try {
        return dataSource.getConnection();
    } catch (SQLException e) {
        e.printStackTrace();
    }

    return null;
}

/**
 * Check if the data pool is connected.
 *
 * @return connected Whether the data pool is connected or not.
 */
public boolean isConnected() {
    try {
        dataSource.getConnection();
    } catch (SQLException e) {
        return false;
    }

    return true;
}

我的pom.xml

<project
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>eu.elraro.dubilets</groupId>
<artifactId>Dubilets</artifactId>
<version>1.0-SNAPSHOT</version>
<repositories>
    <repository>
        <id>bungeecord-repo</id>
        <url>https://oss.sonatype.org/content/repositories/snapshots</url>
    </repository>
</repositories>
<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.1</version>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-shade-plugin</artifactId>
            <version>2.3</version>
            <executions>
                <execution>
                    <phase>package</phase>
                    <goals>
                        <goal>shade</goal>
                    </goals>
                </execution>
            </executions>
            <configuration>
                <createDependencyReducedPom>false</createDependencyReducedPom>
                <artifactSet>
                    <includes>
                        <include>org.slf4j:*</include>
                        <include>com.zaxxer:*</include>
                        <include>org.mariadb.jdbc:*</include>
                        <include>org.javassist:javassist</include>
                    </includes>
                </artifactSet>
            </configuration>
        </plugin>
    </plugins>
</build>
<dependencies>
    <!--Spigot API -->
    <dependency>
        <groupId>org.spigotmc</groupId>
        <artifactId>spigot-api</artifactId>
        <version>1.8.8-R0.1-SNAPSHOT</version>
        <scope>provided</scope>
    </dependency>
    <!--Bukkit API -->
    <dependency>
        <groupId>org.bukkit</groupId>
        <artifactId>bukkit</artifactId>
        <version>1.8.8-R0.1-SNAPSHOT</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>com.zaxxer</groupId>
        <artifactId>HikariCP</artifactId>
        <version>2.4.1</version>
        <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId>org.mariadb.jdbc</groupId>
        <artifactId>mariadb-java-client</artifactId>
        <version>1.2.3</version>
    </dependency>
    <dependency>
        <groupId>com.gmail.filoghost</groupId>
        <artifactId>holographic-displays-api</artifactId>
        <version>2.1.7</version>
        <scope>system</scope>
        <systemPath>${basedir}/lib/HolographicDisplaysAPI_v2.1.7.jar</systemPath>
    </dependency>
</dependencies>

推荐答案

不要同时设置dataSourceClassname和jdbcUrl ...它们是互斥的.为简单起见,我建议使用jdbcUrl.

Don't set both the dataSourceClassname and jdbcUrl ... they are mutually exclusive. For simplicity, I recommend the jdbcUrl.

这篇关于HikariCP连接错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆