美文网首页程序员
[BUG]数据库配置错误,Druid配置不生效,Springbo

[BUG]数据库配置错误,Druid配置不生效,Springbo

作者: Wayne维基 | 来源:发表于2020-07-22 20:45 被阅读0次

BUG表现

测试同学反馈,配置错了一个数据库的IP地址,服务启动没有错误,没有中止服务启动,导致很难查问题,希望能加上报错信息。
数据库配置和网上配置差不多

spring.datasource.url=xxxx
spring.datasource.username=xxx
spring.datasource.password=xxx
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.druid.initial-size=1
spring.datasource.druid.min-idle=1
spring.datasource.druid.max-active=40
spring.datasource.druid.max-wait=5000
spring.datasource.druid.time-between-eviction-runs-millis=60000
spring.datasource.druid.min-evictable-idle-time-millis=300000
spring.datasource.druid.validation-query=SELECT 1 FROM DUAL
spring.datasource.druid.validation-query-timeout=3
spring.datasource.druid.pool-prepared-statements=true
spring.datasource.druid.max-pool-prepared-statement-per-connection-size=20

第一阶段解决

先将日志输出,原来系统用的logback的配置,导致druid的错误日志没有输出
换成log4j.properties的配置解决。
看到报错信息是:连接失败。但是debug进入的时候发现几个新的问题:

1 druid配置没有生效
2 连接失败无限重试
3 初始化75s之后才会提示错误信息,而不是一开始就提示

第二阶段解决

找到错误前第一段日志,定位到代码中,下一个断点

LOG.info("{dataSource-" + this.getID() + "} inited");

顺便看到我们用的druid版本是:1.0.18

找到DruidDataSource的构造方法:
Springboot自动注入会预加载对象,看到其中System.getProperties(),加个断点,
这里只是将系统变量注入,没有我们配置的属性,问题的关键不在这里。

    public DruidDataSource(boolean fairLock){
        super(fairLock);

        configFromPropety(System.getProperties());
    }

然后一路Debug下去,找到了Druid获取连接的代码

    @Override
    public DruidPooledConnection getConnection() throws SQLException {
        return getConnection(maxWait);
    }

这里的maxWait是-1,不是我们配置的max-wait,是第一个问题。
但是这里注入了数据库的url,name和password信息

辅助信息:
debug过程中,看到@PostConstruct注入的类之前,已经有了数据库的
url,name和password信息

所以知道application.properties中数据库的url,name,password相关信息
实在Springboot启动时已经注入了。
ps: 这里需要一点Springboot AutoConfigure相关知识,这里就不补充了,
简单来说,springboot的autoconfigure会去读meta-inf/metadata.json的内容,根据其中内容进行自动配置。

搜索了一下,
我们用的springboot版本下确实有相关信息:

    {
      "name": "spring.datasource.username",
      "type": "java.lang.String",
      "description": "Login user of the database.",
      "sourceType": "org.springframework.boot.autoconfigure.jdbc.DataSourceProperties"
    }

但是没有:
spring.datasource.druid.*
相关信息

问题找到了,是我们用的配置不对,导致application.properties中的配置没有生效。
在网上搜了一下,在pom.xml中添加

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.10</version>
        </dependency>

这样配置druid的配置才能生效。

无限重连:
在druid 1.0.18中,其实不是无限次,是30次,只是给我们感觉是无限次

protected int                                      connectionErrorRetryAttempts              = 30;

升级到1.1.10解决了这个问题,因为他的配置是

protected int                                      connectionErrorRetryAttempts              = 1;

最后一个问题,为什么启动的时候连接是1分15秒之后报错。
这个我们对于connect连接进行debug,发现并没有设置超时时间,或者说我们设置的超时时间是0。
这里的过程比较长,我直接说结论吧。
Connect的建立过程,
1 先尝试druid connect
conn = createPhysicalConnection(url, physicalConnectProperties)

一个责任链来判断druid中谁可以创造连接

     if (this.pos < filterSize) {
            return nextFilter()
                    .connection_connect(this, info);
        }

        Driver driver = dataSource.getRawDriver();
        String url = dataSource.getRawJdbcUrl();

2 因为我们的配置错误,所以走到了:dataSource.getRawDriver()
利用了原始的mysql-connector

Connection newConn = com.mysql.jdbc.ConnectionImpl.getInstance(host(props), port(props), props, database(props), url);

3 其中使用的JDBC connect

return (Connection) Util.handleNewInstance(JDBC_4_CONNECTION_CTOR,
                new Object[] { hostToConnectTo, Integer.valueOf(portToConnectTo), info, databaseToConnectTo, url }, null);
   

4 一番检查和初始化之后MysqlIO,这其中创建的是一个socket连接

this.io = new MysqlIO(newHost, newPort, mergedProps, getSocketFactoryClassName(), getProxy(), getSocketTimeout(),
                this.largeRowSizeThreshold.getValueAsInt());

通过一个工厂类创建socket连接

this.mysqlConnection = this.socketFactory.connect(this.host, this.port, props);

5 又是一番socket的初始化和配置之后,底层调用

    synchronized void doConnect(InetAddress address, int port, int timeout) throws IOException {
        synchronized (fdLock) {
            if (!closePending && (socket == null || !socket.isBound())) {
                NetHooks.beforeTcpConnect(fd, address, port);
            }
        }
        try {
            acquireFD();
            try {
                socketConnect(address, port, timeout);
                /* socket may have been closed during poll/select */
                synchronized (fdLock) {
                    if (closePending) {
                        throw new SocketException ("Socket closed");
                    }
                }
                // If we have a ref. to the Socket, then sets the flags
                // created, bound & connected to true.
                // This is normally done in Socket.connect() but some
                // subclasses of Socket may call impl.connect() directly!
                if (socket != null) {
                    socket.setBound();
                    socket.setConnected();
                }
            } finally {
                releaseFD();
            }
        } catch (IOException e) {
            close();
            throw e;
        }
    }

其中:socketConnect是一个native方法,我们就不继续向下看了。一个默认的初始化连接超时时间在系统底层设置。

    native void socketConnect(InetAddress address, int port, int timeout)
        throws IOException;

其他

  • 查这个问题之后有个经验,配置更优的工程实践还是自己在项目中写一个Config.java文件,Springboot可以通过加入@Configuration的方式注入,
    可以屏蔽不同的版本差异,配置也更可控。
@Configuration
public class DruidConfig {

    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean(name = "dataSource")
    public DataSource druid(){
        return new DruidDataSource();
    }
}

相关文章

网友评论

    本文标题:[BUG]数据库配置错误,Druid配置不生效,Springbo

    本文链接:https://www.haomeiwen.com/subject/ceywkktx.html