侧边栏壁纸
  • 累计撰写 11 篇文章
  • 累计创建 10 个标签
  • 累计收到 3 条评论
隐藏侧边栏

springboot整合带账号和密码的elasticsearch

九怀
2022-01-10 / 0 评论 / 0 点赞 / 107 阅读 / 5,708 字 / 正在检测是否收录...
温馨提示:
本文最后更新于 2022-01-10,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。

springboot整合带账号和密码的elasticsearch

第一步引入elasticsearch依赖

<!--elasticsearch检索服务依赖-->
<dependency>
   <groupId>org.elasticsearch.client</groupId>
   <artifactId>elasticsearch-rest-high-level-client</artifactId>
</dependency>

第二步:编写yml文件

elasticsearch:
  schema: http
  address: 192.168.123.165 #你的服务器地址
  connectTimeout: 5000
  socketTimeout: 5000
  connectionRequestTimeout: 5000
  maxConnectNum: 100
  maxConnectPerRoute: 100
  UserName: elastic #账号
  Password: h123456 #你的elasticsearch密码

第三步:编写config配置文件

package com.atguigu.gulimall.search.config;



import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.List;
/**
 * @Deacription ElasticSearch 配置
 * @Author x
 **/
@Configuration
public class cccccc {

      /**
       * 协议
       */
      @Value("${elasticsearch.schema:http}")
      private String schema;
      
      /**
       * 集群地址,如果有多个用“,”隔开
       */
      @Value("${elasticsearch.address}")
      private String address;
      
      /**
       * 连接超时时间
       */
      @Value("${elasticsearch.connectTimeout}")
      private int connectTimeout;
      
      /**
       * Socket 连接超时时间
       */
      @Value("${elasticsearch.socketTimeout}")
      private int socketTimeout;
      
      /**
       * 获取连接的超时时间
       */
      @Value("${elasticsearch.connectionRequestTimeout}")
      private int connectionRequestTimeout;
      
      /**
       * 最大连接数
       */
      @Value("${elasticsearch.maxConnectNum}")
      private int maxConnectNum;
      
      /**
       * 最大路由连接数
       */
      @Value("${elasticsearch.maxConnectPerRoute}")
      private int maxConnectPerRoute;
      
      @Value("${elasticsearch.UserName}")
      private String userName;
      
      @Value("${elasticsearch.Password}")
      private String password;
   
   
   //通用设置项
   public static final RequestOptions COMMON_OPTIONS;
   static {
      RequestOptions.Builder builder = RequestOptions.DEFAULT.toBuilder();
      // builder.addHeader("Authorization", "Bearer " + TOKEN);
      // builder.setHttpAsyncResponseConsumerFactory(
      //        new HttpAsyncResponseConsumerFactory
      //                  .HeapBufferedResponseConsumerFactory(30 * 1024 * 1024 * 1024));
      COMMON_OPTIONS = builder.build();
   }
      
      // @Bean(name = "restHighLevelClient")
      @Bean
      public RestHighLevelClient restHighLevelClient() {
         // 拆分地址
         List<HttpHost> hostLists = new ArrayList<>();
         String[] hostList = address.split(",");
         for (String addr : hostList) {
            String host = addr.split(":")[0];
            String port = addr.split(":")[1];
            hostLists.add(new HttpHost(host, Integer.parseInt(port), schema));
         }
         
         final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
         credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userName, password));
         
         // 转换成 HttpHost 数组
         HttpHost[] httpHost = hostLists.toArray(new HttpHost[]{});
         // 构建连接对象
         RestClientBuilder builder = RestClient.builder(httpHost);
         // 异步连接延时配置
         builder.setRequestConfigCallback(requestConfigBuilder -> {
            requestConfigBuilder.setConnectTimeout(connectTimeout);
            requestConfigBuilder.setSocketTimeout(socketTimeout);
            requestConfigBuilder.setConnectionRequestTimeout(connectionRequestTimeout);
            return requestConfigBuilder;
         });
         // 异步连接数配置
         builder.setHttpClientConfigCallback(httpClientBuilder -> {
            httpClientBuilder.setMaxConnTotal(maxConnectNum);
            httpClientBuilder.setMaxConnPerRoute(maxConnectPerRoute);
            return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
         });
         return new RestHighLevelClient(builder);
      }
}

第四步测试:

1.没有执行测试方法前在可视化界面查看

在这里插入图片描述

2.执行测试方法
package com.atguigu.gulimall.search;

import com.alibaba.fastjson.JSON;
// import com.atguigu.gulimall.search.config.GulimallFlasticSearchConfig;
import com.atguigu.gulimall.search.config.cccccc;
import lombok.Data;
import org.elasticsearch.action.index.IndexRequest;
// import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.IOException;

@RunWith(SpringRunner.class)
@SpringBootTest
public class GulimallSearchApplicationTests {
   
   @Autowired //注入RestHighLevelClient
   RestHighLevelClient client;
   
   /**
    * 测试存储数据到elasticsearch
    * 更新也可以
    * 文档https://www.elastic.co/guide/en/elasticsearch/client/java-rest/7.9/java-rest-high-document-index.html
    *    1.在可视化界面执行
    *           #查询users索引
    *           GET users/_search
    */
   @Test
   public void indexData() throws IOException {
      //创建索引对象,给users索引存储数据
      IndexRequest indexRequest=new IndexRequest("users");
      //设置唯一标识id
      indexRequest.id("1");
      //"userName","zhangsan","age",18,"gender","男"
      //创建user对象
      User user=new User();
      //给user实体对象赋值
      user.setUserName("zhangsan");
      user.setAge(18);
      user.setGender("男");
      //将user对象转为json格式
      String jsonString = JSON.toJSONString(user);
      //要保存的内容
      indexRequest.source(jsonString, XContentType.JSON);
      
      //执行插入保存操作
      IndexResponse index = client.index(indexRequest, cccccc.COMMON_OPTIONS);
      
      //提取有用的响应数据
      System.out.println(index);
   }
   
   //User实体类
   @Data //get-set方法
   class User{
      private String userName;  //姓名
      private String gender; //性别
      private Integer age; //年龄
   }
   
   
   
   /**
    * 测试获取elasticsearch对象
    */
   @Test
   public void contextLoads() {
      System.out.println(client);
   }

}
3.执行测试方法后查看图形化界面成功

idea显示:

在这里插入图片描述

图形化界面显示:

在这里插入图片描述

================End结束===============

参考:

按照这个设置成功的====================

https://blog.csdn.net/terry711/article/details/115653979

======================================

0

评论区