Elasticsearch 审计
准备实体
为了使审计代码能够判断实体实例是否为新实体,该实体必须实现 Persistable<ID>
接口,该接口定义如下
package org.springframework.data.domain;
import org.springframework.lang.Nullable;
public interface Persistable<ID> {
@Nullable
ID getId();
boolean isNew();
}
由于 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)
}
}
1 | getter 是接口的必需实现 |
2 | 如果对象没有 id 或未设置任何包含创建属性的字段,则该对象是新的。 |
激活审计
在设置实体并提供 AuditorAware
- 或 ReactiveAuditorAware
之后,必须通过在配置类上设置 @EnableElasticsearchAuditing
来激活审计
@Configuration
@EnableElasticsearchRepositories
@EnableElasticsearchAuditing
class MyConfiguration {
// configuration code
}
当使用响应式堆栈时,必须是
@Configuration
@EnableReactiveElasticsearchRepositories
@EnableReactiveElasticsearchAuditing
class MyConfiguration {
// configuration code
}
如果您的代码包含多个用于不同类型的 AuditorAware
bean,则必须提供要用作 @EnableElasticsearchAuditing
注释的 auditorAwareRef
参数的 bean 的名称。