考虑在配置中定义一个名为“ elasticsearchTemplate”的bean

时间:2019-06-07 07:12:33

标签: java spring spring-boot elasticsearch elastic-stack

我刚刚启动springboot并尝试通过spring-boot实现弹性搜索,但是在运行spring-boot应用程序时出现此类错误

  

考虑在您的配置中定义一个名为“ elasticsearchTemplate”的bean。

POM.XML

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-devtools</artifactId>
        </dependency>
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>bootstrap</artifactId>
            <version>4.0.0</version>
        </dependency>
         <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>transport</artifactId>
            <version>5.6.10</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
        </dependency>


    </dependencies>

存储库

@Repository
public interface StudentRepository extends ElasticsearchRepository<Student, Integer>{}

控制器

@RestController
public class Controller {

    @Autowired
    StudentRepository studentRepo;

    @GetMapping(value="/student/all")
    List<Student> getAllStudent() {

        Iterator<Student> studentList = studentRepo.findAll().iterator();
        List<Student> students = new ArrayList<>();
        if(studentList.hasNext()) {
            students.add(studentList.next());
        }
        return students;
    }

    @PostMapping(value="/student/add")
    String addStudent(@RequestBody Student student) {

        studentRepo.save(student);
        return "Record Added Successfully";
    } 

    @DeleteMapping(value="/student/delete/{id}")
    String deleteStudent(@PathVariable int id) {

        studentRepo.deleteById(id);
        return "Record Deleted Successfully";
    }

    //@GetMapping(value="/student/findById/{id}")

}

任何人都可以帮助我解决此错误

  

考虑在您的配置中定义一个名为“ elasticsearchTemplate”的bean。

2 个答案:

答案 0 :(得分:1)

注意:请参考spring-data-elasticsearch-versionsSpring Data Elasticsearch Changelog(检查所需版本的Elasticsearch version)以检查版本兼容性。

解决方案(1):


如果要使用Spring Boot 1.x,只需创建一个@Configuration类并添加一个ElasticsearchOperations Bean。
请注意,Spring Boot 1.x不支持最新版本的ElasticSearch 5.x和更高版本。
cluster.name :确保您在代码中设置的集群名称与您在$ ES_HOME / config / elasticsearch.yml

中设置的集群名称相同。
@Configuration
public class ElasticSearchConfig {

    @Bean
    public ElasticsearchOperations elasticsearchTemplate() throws UnknownHostException {
        return new ElasticsearchTemplate(getClient());
    }

    @Bean
    public Client getClient() throws UnknownHostException {
        Settings setting = Settings
            .builder()
            .put("client.transport.sniff", true)
            .put("path.home", "/usr/share/elasticsearch") //elasticsearch home path
            .put("cluster.name", "elasticsearch")
            .build();
        //please note that client port here is 9300 not 9200! 
        TransportClient client = new PreBuiltTransportClient(setting)
            .addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"), 9300)); 
        return client;
    }
}

解决方案(2):


此外,您还可以参考此spring boot issue,其中显示了弹性数据在来自弹簧靴2.2.0。
因此,使用spring boot 2.2spring-boot-starter-elasticserach不需要手动配置Elasticsearch。

示例工作项目:
版本:
弹簧靴:2.2.0.RELEASE
Elasticsearch:6.6.2

Pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>spring-boot-elasticsearch</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.0.RELEASE</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

</project>

application.properties:

spring.data.elasticsearch.cluster-name=elasticsearch
spring.data.elasticsearch.cluster-nodes=localhost:9300
spring.elasticsearch.jest.uris=http://localhost:9200

主应用程序类:

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

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

模型类:

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

@Document(indexName = "your_index", type = "books")
public class Book {
    @Id
    private String id;
    private String title;
    private String author;
    private String releaseDate;
    //getter, setter/constructors
}

存储库类:

import com.example.model.Book;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.stereotype.Repository;
import java.util.List;

@Repository
public interface BookRepository extends ElasticsearchRepository<Book, String> {

    Page<Book> findByAuthor(String author, Pageable pageable);
    List<Book> findByTitle(String title);
}

服务等级: 一些测试方法:

import com.example.model.Book;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import java.util.List;

public interface BookService {
    Book save(Book book);
    void delete(Book book);
    Book findOne(String id);
    Iterable<Book> findAll();
    Page<Book> findByAuthor(String author, Pageable pageable);
    List<Book> findByTitle(String title);
}

服务实施:

import com.example.model.Book;
import com.example.repository.BookRepository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class BookServiceImpl implements BookService {

    private BookRepository bookRepository;

    public BookServiceImpl(BookRepository bookRepository) {
        this.bookRepository = bookRepository;
    }

    @Override
    public Book save(Book book) {
        return bookRepository.save(book);
    }

    @Override
    public void delete(Book book) {
        bookRepository.delete(book);
    }

    @Override
    public Book findOne(String id) {
        return bookRepository.findById(id).orElse(null);
    }

    @Override
    public Iterable<Book> findAll() {
        return bookRepository.findAll();
    }

    @Override
    public Page<Book> findByAuthor(String author, Pageable pageable) {
        return bookRepository.findByAuthor(author, pageable);
    }

    @Override
    public List<Book> findByTitle(String title) {
        return bookRepository.findByTitle(title);
    }
}

测试课程:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class BookTest {

    @Autowired
    private BookService bookService;

    @Autowired
    private ElasticsearchTemplate esTemplate;

    @Before
    public void before(){
        esTemplate.deleteIndex(Book.class);
        esTemplate.createIndex(Book.class);
        esTemplate.putMapping(Book.class);
        esTemplate.refresh(Book.class);
    }

    @Test
    public void testSave(){
        Book book = new Book("1001", "Elasticsearch", "title", "23-FEB-2017");
        Book testBook = bookService.save(book);
        assertNotNull(testBook.getId());
        assertEquals(testBook.getTitle(), book.getTitle());
        assertEquals(testBook.getAuthor(), book.getAuthor());
        assertEquals(testBook.getReleaseDate(), book.getReleaseDate());
    }
}

答案 1 :(得分:0)

您需要在application.properties文件中定义一些弹性搜索属性,例如cluster-nodescluster-names,这些文件由 ElasticsearchTemplate ElasticsearchRepository 使用>以连接到Elasticsearch引擎。

您可以参考以下提到的链接:

https://dzone.com/articles/elasticsearch-with-spring-boot-application