跳到主要内容

Elasticsearch 审计

DeepSeek V3 中英对照 Elasticsearch Auditing

准备实体

为了使审计代码能够判断实体实例是否为新的,实体必须实现 Persistable<ID> 接口,该接口定义如下:

package org.springframework.data.domain;

import org.springframework.lang.Nullable;

public interface Persistable<ID> {
@Nullable
ID getId();

boolean isNew();
}
java

由于 Id 的存在不足以确定 Elasticsearch 中的实体是否为新实体,因此需要额外的信息。一种方法是使用与创建相关的审计字段来进行判断:

一个 Person 实体可能如下所示 - 为了简洁起见,省略了 getter 和 setter 方法:

@Document(indexName = "person")
public class Person implements Persistable<Long> {
@Id private Long id;
private String lastName;
private String firstName;
@CreatedDate
@Field(type = FieldType.Date, format = DateFormat.basic_date_time)
private Instant createdDate;
@CreatedBy
private String createdBy
@Field(type = FieldType.Date, format = DateFormat.basic_date_time)
@LastModifiedDate
private Instant lastModifiedDate;
@LastModifiedBy
private String lastModifiedBy;

public Long getId() { 1
return id;
}

@Override
public boolean isNew() {
return id == null || (createdDate == null && createdBy == null); 2
}
}
java
  • getter 是接口中要求的实现

  • 如果一个对象没有 id 或者没有设置任何包含创建属性的字段,则该对象是新的。

激活审计

在设置好实体并提供 AuditorAwareReactiveAuditorAware 之后,必须通过在配置类上设置 @EnableElasticsearchAuditing 来激活审计功能:

@Configuration
@EnableElasticsearchRepositories
@EnableElasticsearchAuditing
class MyConfiguration {
// configuration code
}
java

在使用响应式堆栈时,这必须是:

@Configuration
@EnableReactiveElasticsearchRepositories
@EnableReactiveElasticsearchAuditing
class MyConfiguration {
// configuration code
}
java

如果你的代码中包含多个针对不同类型的 AuditorAware bean,你必须提供要使用的 bean 的名称作为 @EnableElasticsearchAuditing 注解的 auditorAwareRef 参数的参数值。