此版本仍在开发中,尚不被认为是稳定的。对于最新的稳定版本,请使用 Spring Data Elasticsearch 5.5.2! |
Elasticsearch 审计
准备实体
为了使审核代码能够确定实体实例是否为新实例,实体必须实现Persistable<ID>
接口,定义如下:
import org.springframework.lang.Nullable;
public interface Persistable<ID> {
@Nullable
ID getId();
boolean isNew();
}
由于 Id 的存在不足以确定 enitity 是否是 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 对于不同类型,您必须提供要用作auditorAwareRef
参数@EnableElasticsearchAuditing
注解。