当前位置:   article > 正文

springboot集成es 超详细步骤_springboot es集成

springboot es集成

我的es是7.18.x   springboot版本为2.7.3

其他版本对应可以去查下,这里就不过多叙述

直接上步骤:

1.导入maven依赖:

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
  4. </dependency>

2.设置配置:

  1. # spring配置
  2. spring:
  3. data:
  4. elasticsearch:
  5. username: your_username
  6. password: your_password
  7. cluster-name: cluster # 你的es集群名称
  8. cluster-nodes: 127.0.0.1:9201,127.0.0.1:9202,127.0.0.1:9203

3.创建一个配置类 ElasticsearchConfig:

  1. import org.apache.http.HttpHost;
  2. import org.apache.http.auth.AuthScope;
  3. import org.apache.http.auth.UsernamePasswordCredentials;
  4. import org.apache.http.client.CredentialsProvider;
  5. import org.apache.http.impl.client.BasicCredentialsProvider;
  6. import org.elasticsearch.client.RestClient;
  7. import org.elasticsearch.client.RestClientBuilder;
  8. import org.elasticsearch.client.RestHighLevelClient;
  9. import org.springframework.beans.factory.annotation.Value;
  10. import org.springframework.context.annotation.Bean;
  11. import org.springframework.context.annotation.Configuration;
  12. import org.springframework.data.elasticsearch.config.AbstractElasticsearchConfiguration;
  13. import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
  14. import java.time.Duration;
  15. /**
  16. * description: 初始化ElasticsearchRestTemplate
  17. * create by: zt
  18. * create time: 2024/4/11 10:16
  19. */
  20. @Configuration
  21. public class ElasticsearchConfig extends AbstractElasticsearchConfiguration {
  22. @Value("${spring.data.elasticsearch.cluster-nodes}")
  23. private String url;
  24. @Value("${spring.data.elasticsearch.username}")
  25. private String username;
  26. @Value("${spring.data.elasticsearch.password}")
  27. private String password;
  28. @Override
  29. @Bean
  30. public RestHighLevelClient elasticsearchClient() {
  31. url = url.replace("http://", "");
  32. String[] urlArr = url.split(",");
  33. HttpHost[] httpPostArr = new HttpHost[urlArr.length];
  34. for (int i = 0; i < urlArr.length; i++) {
  35. HttpHost httpHost = new HttpHost(urlArr[i].split(":")[0].trim(),
  36. Integer.parseInt(urlArr[i].split(":")[1].trim()), "http");
  37. httpPostArr[i] = httpHost;
  38. }
  39. final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
  40. credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
  41. RestClientBuilder builder = RestClient.builder(httpPostArr)
  42. // 异步httpclient配置
  43. .setHttpClientConfigCallback(httpClientBuilder -> {
  44. // 账号密码登录
  45. httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
  46. // httpclient连接数配置
  47. httpClientBuilder.setMaxConnTotal(30);
  48. // 每个路由值指定最大连接数
  49. httpClientBuilder.setMaxConnPerRoute(10);
  50. // httpclient 设置保活策略|长时间不连接es,报错超时连接 每隔五分钟发送一次请求
  51. httpClientBuilder.setKeepAliveStrategy(((response, context) -> Duration.ofMinutes(5).toMillis()));
  52. return httpClientBuilder;
  53. });
  54. return new RestHighLevelClient(builder);
  55. }
  56. @Bean
  57. public ElasticsearchRestTemplate elasticsearchRestTemplate() {
  58. return new ElasticsearchRestTemplate(elasticsearchClient());
  59. }

4.创建一个文档映射实体:

  1. import lombok.AllArgsConstructor;
  2. import lombok.Data;
  3. import lombok.NoArgsConstructor;
  4. import org.springframework.data.annotation.Id;
  5. import org.springframework.data.elasticsearch.annotations.Document;
  6. import org.springframework.data.elasticsearch.annotations.Field;
  7. import org.springframework.data.elasticsearch.annotations.FieldType;
  8. /**
  9. * @Description: TODO
  10. * @Author zt
  11. * @Date 2024/4/11 9:55
  12. * @Version 1.0
  13. */
  14. @Data
  15. @AllArgsConstructor
  16. @NoArgsConstructor
  17. @Document(indexName = "item_index")
  18. public class TestEntity {
  19. @Id
  20. private Long id;
  21. @Field(type = FieldType.Text)
  22. private String title; //标题
  23. @Field(type = FieldType.Keyword)
  24. private String category;// 分类
  25. @Field(type = FieldType.Keyword)
  26. private String brand; // 品牌
  27. @Field(type = FieldType.Double)
  28. private Double price; // 价格
  29. @Field(index = false, type = FieldType.Keyword)
  30. private String images; // 图片地址
  31. }

5.创建一个交互类:

  1. import com.datian.framework.njwst.domain.TestEntity;
  2. import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
  3. import org.springframework.stereotype.Repository;
  4. /**
  5. * @Description: TODO
  6. * @Author zt
  7. * @Date 2024/4/11 9:53
  8. * @Version 1.0
  9. */
  10. @Repository
  11. public interface TestRepository extends ElasticsearchRepository<TestEntity, Long> {
  12. }

6.开始测试使用:

  1. import com.datian.framework.njwst.domain.TestEntity;
  2. import com.datian.framework.njwst.repository.TestRepository;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
  5. import org.springframework.web.bind.annotation.GetMapping;
  6. import org.springframework.web.bind.annotation.RequestMapping;
  7. import org.springframework.web.bind.annotation.RestController;
  8. /**
  9. * @Description: TODO
  10. * @Author zt
  11. * @Date 2024/4/10 17:48
  12. * @Version 1.0
  13. */
  14. @RestController
  15. @RequestMapping("/es")
  16. public class TestController {
  17. @Autowired
  18. private ElasticsearchRestTemplate mRestTemplate;
  19. @Autowired
  20. private TestRepository itemRepository;
  21. @GetMapping("create")
  22. public void createIndex() {
  23. mRestTemplate.indexOps(TestEntity.class).create();
  24. }
  25. @GetMapping("insert")
  26. public void insert() {
  27. TestEntity item = new TestEntity(1L, "小米手机7", "手机", "小米", 2999.00, "https://img12.360buyimg.com/n1/s450x450_jfs/t1/14081/40/4987/124705/5c371b20E53786645/c1f49cd69e6c7e6a.jpg");
  28. itemRepository.save(item);
  29. }
  30. }

此时itemRepository 和我们使用mybatisplus 时基本一致,已经包装了基础的操作类

对于一些简单的查询 也可以直接命名即可

例如:

  1. @Repository
  2. public interface TestRepository extends ElasticsearchRepository<TestEntity, Long> {
  3. List<TestEntity> findByTitle(String title);
  4. }

也可以执行自定义DSL语句:

例如:

  1. @Repository
  2. public interface TestRepository extends ElasticsearchRepository<TestEntity, Long> {
  3. List<TestEntity> findByTitle(String title);
  4. @Query("{\"match\": {\"brand\": \"?0\"}}")
  5. List<TestEntity> findByBrand(String brand);
  6. }

更多操作 可查阅官方api

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/代码探险家/article/detail/785780
推荐阅读
相关标签
  

闽ICP备14008679号