Spring Data Elasticsearch 5.0.x修改数据后无法立即刷新解决方法示例
作者:TinyThing
背景
在项目中用到了Spring Data ElasticSearch,最近更新到了最新版本5.0.x,在数据插入、修改、删除后,紧接着进行查询发现数据并未更新;
解决方法
研究后发现是新版本的spring data es默认的刷新策略是null,代码如下:
@Bean @ConditionalOnMissingBean(value = ElasticsearchOperations.class, name = "elasticsearchTemplate") @ConditionalOnBean(ElasticsearchClient.class) ElasticsearchTemplate elasticsearchTemplate(ElasticsearchClient client, ElasticsearchConverter converter) { return new ElasticsearchTemplate(client, converter); }
这里没有给ElasticsearchTemplate设置refreshPolicy属性,点进AbstractElasticsearchTemplate可以看到默认为null,而以前默认是立即刷新IMMEDIATE。
查看Spring官网发现
Refresh configuration
When configuring Spring Data Elasticsearch like described in Elasticsearch Clients by using ElasticsearchConfigurationSupport, AbstractElasticsearchConfiguration or AbstractReactiveElasticsearchConfiguration the refresh policy will be initialized to null. Previously the reactive code initialized this to IMMEDIATE, now reactive and non-reactive code show the same behaviour.
也就是说,对es数据库进行数据变更操作时,默认是按照索引自带的刷新策略(一般情况下是1s以后才会更新索引)
{ "settings": {}, "defaults": { "index": { "refresh_interval": "1s" } } }
如果想要在Spring data es中更新数据后立即刷新,那么需要如下配置覆盖掉Springboot的Auto Configuration:
@Configuration @EnableConfigurationProperties(ElasticsearchProperties.class) public class ElasticsearchConfig extends ElasticsearchConfiguration { private final ElasticsearchProperties properties; public ElasticsearchConfig(ElasticsearchProperties properties) { this.properties = properties; } @NotNull @Override public ClientConfiguration clientConfiguration() { List<String> uris = properties.getUris(); String[] uri = uris.toArray(new String[0]); return ClientConfiguration.builder() .connectedTo(uri) .withSocketTimeout(properties.getSocketTimeout()) .withConnectTimeout(properties.getConnectionTimeout()) .build(); } @NotNull @Bean(name = { "elasticsearchOperations", "elasticsearchTemplate" }) @Override public ElasticsearchOperations elasticsearchOperations(@NotNull ElasticsearchConverter elasticsearchConverter, @NotNull ElasticsearchClient elasticsearchClient) { ElasticsearchTemplate template = new ElasticsearchTemplate(elasticsearchClient, elasticsearchConverter); template.setRefreshPolicy(RefreshPolicy.IMMEDIATE); return template; } }
以上就是Spring Data Elasticsearch 5.0.x修改数据后无法立即刷新解决方法示例的详细内容,更多关于Spring Data Elasticsearch无法刷新的资料请关注脚本之家其它相关文章!