我是靠谱客的博主 年轻小霸王,最近开发中收集的这篇文章主要介绍SpringBoot 整合 elasticsearch 遇到的问题,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

SpringBoot 整合 elasticsearch 遇到的问题

一、使用到的版本

  • elasticsearch -7.17-4
  • SpringBoot 版本在这里插入图片描述- 导入相关的包
    在这里插入图片描述- 官方版本
    在这里插入图片描述 https://docs.spring.io/spring-data/elasticsearch/docs/current/reference/html/#preface.versions

二、程序中的代码

  • 入口类

@SpringBootApplication
public class CommunityApplication {

	@PostConstruct
	public void intit(){
		// 解决netty启动冲突问题
		// see NettyUtils.setAvailableProcessors()
		System.setProperty("es.set.netty.runtime.available.processors", "false");
	}
	public static void main(String[] args) {
		SpringApplication.run(CommunityApplication.class, args);
	}

}

- 项目中使用了Redis,解决netty冲突问题
  • 实体类中进行注解配置
@Document(indexName = "discusspost",shards = 3,replicas =2 )
public class DiscussPost {
    @Id
    private int id;
    @Field(type = FieldType.Integer)
    private int userId;
    /**
     * analyzer 存入es 的解析器
     * searchAnalyzer 搜索es的解析器
     */
    @Field(type = FieldType.Text,analyzer = "ik_max_word",searchAnalyzer ="ik_smart" )
    private String title;

    @Field(type = FieldType.Text,analyzer = "ik_max_word",searchAnalyzer ="ik_smart" )
    private String content;

    @Field(type = FieldType.Integer)
    private int type;
 
    @Field(type = FieldType.Integer)
    private int status;
    @Field(type = FieldType.Date)
    private Date createTime;

    @Field(type = FieldType.Integer)
    private int commentCount;
    // 分数 最后进行推荐
    @Field(type = FieldType.Double)
    private double score;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getUserId() {
        return userId;
    }

    public void setUserId(int userId) {
        this.userId = userId;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public int getType() {
        return type;
    }

    public void setType(int type) {
        this.type = type;
    }

    public int getStatus() {
        return status;
    }

    public void setStatus(int status) {
        this.status = status;
    }

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    public int getCommentCount() {
        return commentCount;
    }

    public void setCommentCount(int commentCount) {
        this.commentCount = commentCount;
    }

    public double getScore() {
        return score;
    }

    public void setScore(double score) {
        this.score = score;
    }

   
}

  • 在dao层中定义了一个接口,去继承ElasticsearchRepository ,里面有封装好的一些基本方法
// Repository 是 spring 对于持久层的注解
// ElasticsearchRepository 封装好了对于es的增删改查的方法
@Repository
public interface DiscussPostRepository extends ElasticsearchRepository<DiscussPost,Integer> {

}

  • ElasticsearchRepository 继承 PagingAndSortingRepository 继承 CrudRepository中我有的方法
    在这里插入图片描述

配置文件的问题

当按照之前配置发现,idea已经出现红色的波浪线,具体的提示如下:

Deprecated configuration property 'spring.data.elasticsearch.cluster-nodes' less... (Ctrl+F1) 
Inspection info: Checks Spring Boot application .properties configuration files. Highlights unresolved and deprecated configuration keys and invalid values

翻译过来大概就是:突出显示未解析和已弃用的配置键和无效值

   @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    @Test
    public void testInsert(){
        elasticsearchTemplate.save(discussPostMapper.selectDiscussPostById(275));
    }
  • 忽视配置文件的提示进行测试会出现如下的错误:
java.lang.IllegalStateException: Failed to load ApplicationContext
	.......
	at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:132)
	com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
	Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'discussPostRepository' defined in com.nowcoder.community.dao.elasticsearch.DiscussPostRepository 
	defined in @EnableElasticsearchRepositories declared on ElasticsearchRepositoriesRegistrar.EnableElasticsearchRepositoriesConfiguration: Invocation of init method failed; nested exception is org.springframework.beans.BeanInstantiationException: 
	Failed to instantiate [org.springframework.data.elasticsearch.repository.support.SimpleElasticsearchRepository]: Constructor threw exception; nested exception is org.springframework.data.elasticsearch.UncategorizedElasticsearchException: 
	java.util.concurrent.ExecutionException: java.net.ConnectException: Timeout connecting to [localhost/127.0.0.1:9200]; nested exception is ElasticsearchException[java.util.concurrent.ExecutionException: 
	java.net.ConnectException: Timeout connecting to [localhost/127.0.0.1:9200]]; nested: ExecutionException
	[java.net.ConnectException: Timeout connecting to [localhost/127.0.0.1:9200]];
	 nested: ConnectException[Timeout connecting to [localhost/127.0.0.1:9200]];
  • 主要就是 ConnectException[Timeout connecting to [localhost/127.0.0.1:9200]]; 这就说明在application.properties配置并没有其作用

使用 配置类 进行配置

@Configuration
public class ElasticsearchConfig  {

    @Bean
    public RestHighLevelClient restHighLevelClient(){
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("192.168.239.131", 9200,  "http"))) ;
        return client;
    }
}
  • 再次执行测试代码,发现错误发生了变化:
 Unsatisfied dependency expressed through field 'elasticsearchTemplate'; 
 nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.data.elasticsearch.client.elc.ElasticsearchTemplate' available: expected at least 1 bean which qualifies as autowire candidate. 
 Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
  • 从网上查了一下,ElasticSearch7.x版本已经弃用了ElasticSearchTemplate,进而使用ElasticSearchRestTemplate。

解决问题

  • 将 ElasticsearchTemplate 换成 ElasticsearchRestTemplate
 @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;


    @Test
    public void testInsert(){
        elasticsearchRestTemplate.save(discussPostMapper.selectDiscussPostById(275));
    }
  • 运行测试代码
    在这里插入图片描述
  • 使用 postman 查看结果,成功

总结

  • 感觉主要是对于SpringBoot和Elasticsearch版本兼容性和对于Elasticsearch有些弃用方法要提前了解,不然就很容易出现各种问题。
  • 本人处于小白学习阶段,如文章有任何问题请指出,感谢。

最后

以上就是年轻小霸王为你收集整理的SpringBoot 整合 elasticsearch 遇到的问题的全部内容,希望文章能够帮你解决SpringBoot 整合 elasticsearch 遇到的问题所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(36)

评论列表共有 0 条评论

立即
投稿
返回
顶部