SpringBoot整合ElasticSearch

一、先记录一下自己傻逼导致的错误,耗费了很长时间才解决

java.io.IOException: Request PUT http://47.107.74.116:9200/yao/news/1 HTTP/1.1 yielded text/plain; charset=UTF-8, should be json: HTTP/1.1 400 Bad Request
	at io.searchbox.client.http.JestHttpClient.deserializeResponse(JestHttpClient.java:207)
	at io.searchbox.client.http.JestHttpClient.execute(JestHttpClient.java:68)
	at io.searchbox.client.http.JestHttpClient.execute(JestHttpClient.java:60)
	at com.dxy.es.controller.EsController.insertIndex(EsController.java:27)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:497)
	at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190)
	at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
	at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:106)
	at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:888)
	at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:793)
	at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
	at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040)
	at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943)
	at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
	at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
	at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)

测试Jest操作ES,报HTTP/1.1 yielded text/plain; charset=UTF-8, should be json: HTTP/1.1 400 Bad Request错,说是因为response的content-type是 text/plain; charset=UTF-8而不是需要的application/json; charset=UTF-8,因此抛出异常。

最后发现是如下的配置导致的,为啥我要配置下面那两行呢,是因为第一行配置显示已过期,我就想着有没有其他配置替代,源码里面就找到了后面两行,抱着试一试的心态加上了,后来忘了去掉就造成了这么傻逼的错误

spring.elasticsearch.jest.uris=http://47.107.74.116:9200
##下面两行配置启用了proxy代理,导致上面的错误发生
#spring.elasticsearch.jest.proxy.host=47.107.74.116
#spring.elasticsearch.jest.proxy.port=9200

二、如果在docker中启动elasticsearch容器过一段时间就会自动关闭,请参考https://blog.csdn.net/qq_41754409/article/details/94134747

三、编写代码

 1、父pom.xml



    4.0.0

    com.dxy
    springboot-parent
    0.0.1-SNAPSHOT
    
    pom

    
    
        springboot-elasticsearch
        springboot-rabbitmq
        springboot-cache
    

    
    
        org.springframework.boot
        spring-boot-starter-parent
        2.2.1.RELEASE
         
    

    
    
        
        UTF-8
        UTF-8
        1.8
        true
    

    
    
        
            org.springframework.boot
            spring-boot-starter-web
        
        
            org.springframework.boot
            spring-boot-starter
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
    

2、子模块pom.xml



    4.0.0
    
        com.dxy
        springboot-parent
        0.0.1-SNAPSHOT
    
    springboot-elasticsearch
    springboot-elasticsearch
    Demo project for Spring Boot
    jar

    
        
            org.springframework.boot
            spring-boot-starter-data-elasticsearch
        

        
        
            io.searchbox
            jest
            5.3.3
        

    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    

3、application.properties

spring.elasticsearch.jest.uris=http://xx.xx.xx.xx:9200

spring.data.elasticsearch.cluster-name=docker-cluster
spring.data.elasticsearch.cluster-nodes=xx.xx.xx.xx:9300

4、pojo

package com.dxy.es.pojo;

import org.springframework.data.elasticsearch.annotations.Document;

@Document(indexName = "yao",type = "book")
public class Book {

    private Integer id;
    private String bookName;
    private String author;

    public Integer getId() {
        return id;
    }

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

    public String getBookName() {
        return bookName;
    }

    public void setBookName(String bookName) {
        this.bookName = bookName;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    @Override
    public String toString() {
        return "Book{" +
                "id=" + id +
                ", bookName='" + bookName + '\'' +
                ", author='" + author + '\'' +
                '}';
    }
}
package com.dxy.es.pojo;

import io.searchbox.annotations.JestId;

import java.io.Serializable;

public class News implements Serializable {

    @JestId
    private Integer id;
    private String author;
    private String title;
    private String content;


    public Integer getId() {
        return id;
    }

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

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    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;
    }
}

5、ElasticsearchRepository

package com.dxy.es.repository;

import com.dxy.es.pojo.Book;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;

import java.util.List;

public interface BookRepository extends ElasticsearchRepository {

    //该命名方式可参考:https://docs.spring.io/spring-data/elasticsearch/docs/3.2.3.RELEASE/reference/html/#elasticsearch.query-methods
    List findByBookNameLike(String bookName);
}

6、测试代码

package com.dxy.es;

import com.dxy.es.pojo.Book;
import com.dxy.es.pojo.News;
import com.dxy.es.repository.BookRepository;
import io.searchbox.client.JestClient;
import io.searchbox.core.Index;
import io.searchbox.core.Search;
import io.searchbox.core.SearchResult;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.IndexQuery;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.IOException;
import java.util.List;

@RunWith(SpringRunner.class)
@SpringBootTest
class SpringbootElasticsearchApplicationTests {

    @Autowired
    JestClient jestClient;

    @Autowired
    BookRepository bookRepository;

    @Autowired
    ElasticsearchTemplate elasticsearchTemplate;

    @Test
    public void test3(){
        Book book = new Book();
        book.setId(1);
        book.setBookName("Java编程思想");
        book.setAuthor("zhangsan");
        IndexQuery indexQuery = new IndexQuery();
        indexQuery.setId("1");
        indexQuery.setObject(book);
        indexQuery.setIndexName("yao");
        indexQuery.setType("book");
        elasticsearchTemplate.index(indexQuery);
    }

    @Test
    public void test1(){
        Book book = new Book();
        book.setId(100);
        book.setBookName("Java编程思想");
        book.setAuthor("zhangsan");
        bookRepository.index(book);
    }

    @Test
    public void test2(){
        List books = bookRepository.findByBookNameLike("思想");
        for(Book book:books){
            System.out.println(book);
        }
    }

    @Test
    void exIndexLoads() {
        News news = new News();
        news.setId(1);
        news.setAuthor("ccf");
        news.setTitle("abc");
        news.setContent("Jay Chou play part in Chongqing");
        Index build = new Index.Builder(news).index("yao").type("news").build();
        try {
            jestClient.execute(build);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @Test
    public void search() throws IOException {
        String str = "{\n" +
                "    \"query\" : {\n" +
                "        \"match\" : {\n" +
                "            \"about\" : \"rock climbing\"\n" +
                "        }\n" +
                "    }\n" +
                "}";
        Search search = new Search.Builder(str).addIndex("megacorp").addType("employee").build();
        SearchResult jestResult = jestClient.execute(search);
        System.out.println(jestResult.getJsonString());
    }

}

7、启动类

package com.dxy.es;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 *SpringBoot默认使用Spring Data ElasticSearch 进行处理,除此之外SpringBoot还实现了Jest的自动配置
 *    1、Jest自动配置(默认不生效,需要导入 io.searchbox.client.JestClient)
 *       JestClient:操作ES的客户端
 *   2、SpringData ElasticSearch(可能存在版本不一致的情况) 自动配置
 *      Client:客户端,节点信息clusterNodes;clusterName
 *      ElasticsearchTemplate:操作模板
 *      编写一个ElasticsearchRepository的子接口来操作ES
 *  两种用法:https://github.com/spring-projects/spring-data-elasticsearch
 *     1)、编写ElasticsearchRepository的子接口
 *     2)、ElasticsearchTemplate
 *
 */
@SpringBootApplication
public class SpringbootElasticsearchApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootElasticsearchApplication.class, args);
    }

}

 

你可能感兴趣的:(elasticsearch,SpringBoot)