Spring Data访问Elasticsearch----Elasticsearch审计Auditing
- 一、准备实体
- 二、激活审计
一、准备实体
为了让审计代码能够判断一个实体实例是否是新的,实体必须实现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
}
当使用响应式(reactive)堆栈时,必须是:
@Configuration
@EnableReactiveElasticsearchRepositories
@EnableReactiveElasticsearchAuditing
class MyConfiguration {
// configuration code
}
如果您的代码包含多个不同类型的AuditorAware bean,则必须提供bean的名称,作为@EnableElasticsearchAuditing注解的auditorAwareRef的参数。