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有些弃用方法要提前了解,不然就很容易出现各种问题。
  • 本人处于小白学习阶段,如文章有任何问题请指出,感谢。
  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
SpringBoot整合Elasticsearch常用API主要包括以下几个方面: 1. 配置Elasticsearch信息 首先需要在application.yml中配置Elasticsearch的连接信息: ``` spring: data: elasticsearch: cluster-name: elasticsearch cluster-nodes: 127.0.0.1:9300 ``` 2. 创建ElasticsearchRepository 在SpringBoot中,可以通过ElasticsearchRepository来访问Elasticsearch,只需要继承该接口即可。 ``` public interface UserRepository extends ElasticsearchRepository<User, Long> { } ``` 其中,User是实体类,Long是主键类型。 3. 创建实体类 创建实体类,使用注解来映射Elasticsearch中的索引和字段。 ``` @Document(indexName = "user", type = "_doc") public class User { @Id private Long id; @Field(type = FieldType.Keyword) private String name; @Field(type = FieldType.Integer) private Integer age; // getter and setter } ``` 4. 增删改查 通过ElasticsearchRepository提供的方法,可以实现增删改查的操作。如下: ``` @Autowired UserRepository userRepository; // 新增 userRepository.save(user); // 删除 userRepository.deleteById(id); // 修改 userRepository.save(user); // 查询 Optional<User> optional = userRepository.findById(id); ``` 5. 搜索 Elasticsearch提供了丰富的搜索API,可以通过QueryBuilder来构建查询条件,通过SearchRequest来执行搜索操作。如下: ``` @Autowired RestHighLevelClient restHighLevelClient; // 构建查询条件 QueryBuilder queryBuilder = QueryBuilders.matchQuery("name", "张三"); // 构建SearchRequest SearchRequest searchRequest = new SearchRequest("user"); searchRequest.types("_doc"); SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); searchSourceBuilder.query(queryBuilder); searchRequest.source(searchSourceBuilder); // 执行搜索 SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT); // 处理搜索结果 SearchHits hits = searchResponse.getHits(); for (SearchHit hit : hits) { String sourceAsString = hit.getSourceAsString(); User user = JSON.parseObject(sourceAsString, User.class); System.out.println(user); } ``` 以上就是SpringBoot整合Elasticsearch常用API的介绍。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值