查询以终止超过 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/
此页面是否有帮助?