3

我正在开发一个连接到逻辑复制槽的应用程序,以使用 WAL 事件。然后将这些 WAL 事件转发到 MQ 代理。这很好用,但我注意到一段时间后我的内存不足。我设法将问题最小化为负责获取 WAL 事件的代码。它发生在以下代码中:

final Properties properties = new Properties();

PGProperty.USER.set(properties, "user");
PGProperty.PASSWORD.set(properties, "password");
PGProperty.ASSUME_MIN_SERVER_VERSION.set(properties, "9.4");
PGProperty.REPLICATION.set(properties, "database");
PGProperty.PREFER_QUERY_MODE.set(properties, "simple");

while (true) {
    Connection          connection   = null;
    PGConnection        PGConnection = null;
    PGReplicationStream stream       = null;

    try {
        connection = DriverManager.getConnection("jdbc:postgresql://localhost:5432/db", properties);
        PGConnection = connection.unwrap(PGConnection.class);
        stream = PGConnection.getReplicationAPI().replicationStream().logical().withSlotName("slot").start();

        while (true) {
            final ByteBuffer buffer = stream.read();

            // ... logic here ... (disabled during memory test)

            stream.setAppliedLSN(stream.getLastReceiveLSN());
            stream.setFlushedLSN(stream.getLastReceiveLSN());
        }
    } catch (final SQLException e1) {
        Logger.getLogger(getClass()).error(e1);

        if (stream != null) {
            try {
                stream.close();
            } catch (final SQLException e2) {
                Logger.getLogger(getClass()).error(e2);
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (final SQLException e2) {
                Logger.getLogger(getClass()).error(e2);
            }
        }
    }
}

我注释掉了解析消息并将其转发到 MQ 代理的逻辑,因为没有这个也会发生内存不足。

我还尝试通过使用轮询方法readPending()而不是阻塞方法来更改此示例read()(如https://jdbc.postgresql.org/documentation/head/replication.html所示),但问题仍然存在。

我还注意到,过了一会儿,应用程序的 CPU 使用率达到了 100%。这一定是由底层库引起的,因为此时read()仍在正常处理(也就是说,它按顺序处理每个 WAL 事件)。

在这些测试期间,我以低速率执行INSERT和查询。UPDATE

我正在使用以下依赖项:

<dependency>
    <groupId>org.postgresql</groupId>
    <artifactId>postgresql</artifactId>
    <version>42.1.4</version>
</dependency>

该应用程序在 Tomcat8 容器中作为 WAR 运行。

知道发生了什么吗?

更新 1

我弄清楚发生了什么,但到目前为止无法解释。我会详细说。

如前所述,我每隔 10 秒就会进行一次INSERT查询UPDATE。这些查询导致 645 个 WAL 事件。所以每 10 秒,我就有read()645 个事件。一开始,read()一个事件需要 0(或有时 1)毫秒。一段时间后,需要 1 毫秒。然后,再过一段时间,它需要 2 毫秒。等等...

所以过了一段时间,我无法read()在 10 秒内完成 645 个事件,因为所需的时间read()不断增加。这解释了 100% 的 CPU 使用率和内存不足。

我仍然不确定如何解释以及如何解决这个问题。我会继续调查。

更新 2

我尝试buffer.clear()在循环结束时添加,但没有成功。我仍然遇到 100% CPU 和内存问题。正如预期的那样,因为缓冲区是一个局部变量,所以它在每次循环之后都会以任何方式进行 GC。但我认为无论如何测试都是个好主意。

4

1 回答 1

1

我找到了内存不足的原因。我正在使用decoderbufs解码输出插件https://github.com/xstevens/decoderbufs进行测试。当用内置test插件或wal2jsonhttps://github.com/eulerto/wal2json)替换时,我没有这些问题。

我会尽量通知decoderbufs插件的作者。

于 2017-09-15T19:20:37.940 回答