今天是 :

spring boot 向 elasticsearch中写入数据

1 . elasticsearch环境 : application.yaml文件中

# 静态资源前缀
spring:
  mvc:
    static-path-pattern: /static/**


# elasticsearch 配置
elasticsearch:
      url: "192.168.10.116:9200"
      username: "elastic"
      password: "123456"

# 开启调试
debug: true

#端口
server:
  port: 8080

 

2.  自动配置

  package com.zqh.boot.com.zqh.boot.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.apache.http.impl.nio.client.HttpAsyncClientBuilder;
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 org.springframework.data.elasticsearch.config.AbstractElasticsearchConfiguration;
import org.thymeleaf.util.StringUtils;

@Configuration
public class EsConfig extends AbstractElasticsearchConfiguration {



    @Value("${elasticsearch.url}")
    private String url;

    @Value("${elasticsearch.username}")
    private String username;

    @Value("${elasticsearch.password}")
    private String password;


    @Override
    @Bean
    public RestHighLevelClient elasticsearchClient() {

        if(StringUtils.isEmpty(url)) {
              throw new RuntimeException("请先配置elasticsearch.url");
        }

        String[] urls = url.split(",");
        HttpHost[] hostArr = new HttpHost[urls.length];

        for ( int i =0 ; i < urls.length ; i++) {
            String urlstr = urls[i];
            if(StringUtils.isEmpty(urlstr)){
                continue;
            }

            hostArr[i] = HttpHost.create(urlstr);
        }


        final CredentialsProvider credentialsprovider = new BasicCredentialsProvider();
        credentialsprovider.setCredentials(AuthScope.ANY , new UsernamePasswordCredentials(this.username , this.password));
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(hostArr).setHttpClientConfigCallback(
                        new RestClientBuilder.HttpClientConfigCallback() {
                            @Override
                            public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
                                httpClientBuilder.disableAuthCaching();

                                return httpClientBuilder.setDefaultCredentialsProvider(credentialsprovider);
                            }
                        }
                )

        );

        return client;
    }

}

 

3. 创建实体类

package com.zqh.boot.com.zqh.boot.data.es;


import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;

import java.util.Date;


@Data
@Document(indexName = "ryan")
public class RyanEs {

    @Id
    private Integer id;

    private  String name;

    private Date createTime;


}

4. 创建连接器

package com.zqh.boot.com.zqh.boot.com.zqh.boot.com.zqh.boot.mapper;

import com.zqh.boot.com.zqh.boot.data.es.RyanEs;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;

public interface EsRyanTest  extends ElasticsearchRepository<RyanEs, String> {
}

 

5 测试写入

 /**
     *  新增数据
     * */
    @RequestMapping("/esrecord")
    public Object esrecord(){

        RyanEs r  = new RyanEs();
        r.setId(33);
        r.setName("测试测试测试aaaa");
        r.setCreateTime(new Date());

        return esryan.save(r);

    }
    
     // 查询es数据
    @RequestMapping("/esearch/{id}")
    public Object esSearch( @PathVariable String id){
      Optional<RyanEs> r  =  esryan.findById(id);
      if(r.isPresent()){
          return r.get();
      }
      return null;
    }

 

参考:     www.elastic.co/guide/en/elasticsearch/client/java-rest/current/java-rest-high.html

 

公告:

  本站采用 gin作为后台服务
前端使用 sematicui 框架搭建(拼凑)。
有喜欢本站的同学。欢迎到聊天室留言

评论: