知识库

终止超过X秒且不含特定关键字的事务查询

在 Neo4j 中,我们目前有一个名为“执行守卫”的配置属性

dbms.transaction.timeout=30s

可以自动设置为终止运行时间超过“x”秒的事务(x 等于 dbms.transaction.timeout 的值,本例中为 30 秒)。然而,这是全局设置,无法针对特定用户或查询类型进行控制。

因此,为了实现此功能,可以编写并安排一个小型脚本来运行并终止运行时间超过 30 秒的查询。此脚本可以通过 cypher-shell 触发。终止不属于 LOAD CSV 且运行时间超过 30 秒的事务的查询可以编写为:

call dbms.listQueries() yield query, elapsedTimeMillis, queryId, username
where  NOT query contains toLower(“LOAD")
and elapsedTimeMillis >30000
with query, collect(queryId) as q
call dbms.killQueries(q) yield queryId
return query, queryId

终止执行查询的用户不是“neo4j”且运行时间超过 30 秒的事务的查询:

call dbms.listQueries() yield query, elapsedTimeMillis, queryId, username
where  NOT username contains toLower("neo4j")
and elapsedTimeMillis >30000
with query, collect(queryId) as q
call dbms.killQueries(q) yield queryId
return query, queryId

您可以根据查询的某些参数或不应被终止的某些用户修改上述查询。

注意:这仅适用于 Neo4j 3.1 及更高版本!

到目前为止,一切顺利。如果我们将上述查询执行一次,它将一次性检查那些长时间运行的查询。到目前为止,没有重复执行。为了实现自动化,我们可以使用 apoc:

CALL apoc.periodic.repeat("kill long-running queries", "
    call dbms.listQueries() yield query, elapsedTimeMillis, queryId, username
    where NOT username contains toLower("neo4j")
    and elapsedTimeMillis >30000
    with query, collect(queryId) as q
    call dbms.killQueries(q) yield queryId
    return query, queryId
", 10)

在这种情况下,检查长时间运行查询的查询将每十秒钟在执行 apoc 命令的实例和数据库上执行。请根据您的需要调整时间参数。

如果您想手动取消作业,可以使用:

CALL apoc.periodic.cancel("kill long-running queries")

请注意,通过 apoc.periodic.repeat 添加的作业在数据库重启后不会保留。因此,如果我们要永久安装它,我们可以使用 apoc 的初始化脚本(https://neo4j.ac.cn/labs/apoc/4.4/operational/init-script/

将以下行添加到您的 conf/apoc.conf 文件中(另请参阅 https://neo4j.ac.cn/labs/apoc/4.4/config/):

apoc.initializer.cypher.1=CALL apoc.periodic.repeat("kill long-running queries", "CALL dbms.listQueries() yield query, elapsedTimeMillis, queryId, username WHERE username contains toLower('neo4j') AND elapsedTimeMillis > 10000 WITH query, collect(queryId) as q CALL dbms.killQueries(q) yield queryId return query, queryId", 10)

请注意,这是实例级别设置,适用于所有数据库。

您可能希望使用磁盘上的专用 Cypher 文件来存储查询,这样配置文件中就不会有复杂的查询。下面是一个示例:https://neo4j.ac.cn/labs/apoc/4.4/operational/init-script/

© . All rights reserved.