接上一篇内容一文读懂SpringBoot整合Elasticsearch(一)
下面是完整的代码示例,可以参考实现自己的应用程序。
- pom.xml文件
phpCopy code<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-web</artifactId>
</dependency>
</dependencies>
- application.properties文件
kotlinCopy codespring.data.elasticsearch.cluster-nodes=localhost:9300
spring.data.elasticsearch.cluster-name=my-application
- Book实体类
kotlinCopy codeimport org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
@Document(indexName = "book", type = "novel")
public class Book {
@Id
private String id;
private String title;
private String author;
// getter and setter methods
}
- BookRepository接口
kotlinCopy codeimport org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
public interface BookRepository extends ElasticsearchRepository<Book, String> {
}
- BookController类
lessCopy codeimport org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/book")
public class BookController {
@Autowired
private BookRepository bookRepository;
@PostMapping("/")
public Book addBook(@RequestBody Book book) {
return bookRepository.save(book);
}
@GetMapping("/{id}")
public Book getBook(@PathVariable String id) {
return bookRepository.findById(id).orElse(null);
}
@GetMapping("/")
public List<Book> searchBook(@RequestParam String keyword) {
return bookRepository.findByTitleOrAuthor(keyword, keyword);
}
}
- 测试代码
javaCopy code@RunWith(SpringRunner.class)
@SpringBootTest
public class BookControllerTest {
@Autowired
private BookController bookController;
@Test
public void addBook() {
Book book = new Book();
book.setTitle("The Lord of the Rings");
book.setAuthor("J.R.R. Tolkien");
bookController.addBook(book);
}
@Test
public void getBook() {
Book book = bookController.getBook("1");
Assert.assertNotNull(book);
Assert.assertEquals("The Lord of the Rings", book.getTitle());
Assert.assertEquals("J.R.R. Tolkien", book.getAuthor());
}
@Test
public void searchBook() {
List<Book> bookList = bookController.searchBook("Rings");
Assert.assertTrue(bookList.size() > 0);
}
}
以上是一个简单的Spring Boot整合Elasticsearch的示例,供读者参考。