Elasticsearch 审计
准备实体
为了让审计代码能够判断实体实例是否为新实体,该实体必须实现 Persistable<ID> 接口,该接口定义如下
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,则必须提供要使用的 bean 的名称作为 @EnableElasticsearchAuditing 注解的 auditorAwareRef 参数的参数。