spring boot2 + mybatis + elasticsearch6.2.4 + mysql 整合(2)——ElasticSearch初尝

资料查找说明

田守枝java技术博客:http://www.tianshouzhi.com/api/tutorials/springboot/101

fantasic_van的博客:https://blog.csdn.net/fantasic_van/article/details/79309665

天涯泪小武的博客:https://blog.csdn.net/tianyaleixiaowu/article/details/72833940

Spring Data Elasticsearch:

https://docs.spring.io/spring-data/elasticsearch/docs/current/reference/html/#project

小盒子的博客:https://blog.csdn.net/m0_37044606/article/details/79793125

官方文档:https://www.elastic.co/guide/en/elasticsearch/reference/current/index.html

1  项目目录


2  整合ElasticSearch

2.1  model

       案例背景:每个文章(Article)都要属于一个教程(Tutorial),而且每个文章都要有一个作者(Author)。

Tutorial.java

    public class Tutorial implements Serializable{
        private Long id; //教程id
	    private String name;//教程名称
        //setters and getters
        //toString
    }

Author.java

    public class Author implements Serializable {
        private Long id;  //作者id
        private String name;  //作者姓名
        private String remark;  //作者简介
        //setters and getters
        //toString
    }

Article.java

@Document(indexName="ESDome",type="article",indexStoreType="fs",shards=5,replicas=1,refreshInterval="-1")
    public class Article implements Serializable {
        @Id
        private Long id;
        private String title;  //标题
        private String abstracts;  //摘要
        private String content;  //内容
        private Date postTime;  //发表时间
        private Long clickCount;  //点击率
        private Author author;	//作者
        private Tutorial tutorial;  //所属教程
        //setters and getters
        //toString
    }

2.2  dao

    public interface ArticleSearchRepository extends ElasticsearchRepository<Article, Long> {}

2.3  controller

       简单实现一个新增文章和搜索关键字的功能:

@RestController
public class EsController {
    @Autowired
    private ArticleSearchRepository articleSearchRepository;

    @RequestMapping("/add")
    public void testSaveArticleIndex() {
        Author author = new Author();
        author.setId(1L);
        author.setName("tianshouzhi");
        author.setRemark("java developer");

        Tutorial tutorial = new Tutorial();
        tutorial.setId(1L);
        tutorial.setName("elastic search");

        Article article = new Article();
        article.setId(1L);
        article.setTitle("springboot integreate elasticsearch");
        article.setAbstracts("springboot integreate elasticsearch is very easy");
        article.setTutorial(tutorial);
        article.setAuthor(author);
        article.setContent("elasticsearch based on lucene,"
                + "spring-data-elastichsearch based on elaticsearch"
                + ",this tutorial tell you how to integrete springboot with spring-data-elasticsearch");
        article.setPostTime(new Date());
        article.setClickCount(1L);

        articleSearchRepository.save(article);
    }

    @RequestMapping("/query")
    public void testSearch() {
        String queryString = "springboot";//搜索关键字
        QueryStringQueryBuilder builder = new QueryStringQueryBuilder(queryString);
        Iterable<Article> searchResult = articleSearchRepository.search(builder);
        Iterator<Article> iterator = searchResult.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }
}

报错如下:

failed to load elasticsearch nodes : 
org.elasticsearch.client.transport.NoNodeAvailableException: 
None of the configured nodes are available: 
[{#transport#-1}{nO9E5fmjSoWVUxduQ_MZDg}{localhost}{127.0.0.1:9300}]
解决办法:将elasticsearch设置为windows系统服务,并开启

3  测试

3.1  add

在浏览器上输入URL:http://localhost:8080/add


使用chrome插件Sense查看结果:


3.2  查询

       在浏览器上输入URL:http://localhost:8080/query

        在控制台上显示:


4  增加service及其实现类

4.1  项目结构


把control类的内容迁移到service上

EsController.java

@RestController
public class EsController {    
    @Autowired
    private EsService esServiceImpl;
    
    @RequestMapping("/add")
    public void testSaveArticleIndex() {        
        esServiceImpl.save();
    }

    @RequestMapping("/query")
    public void testSearch() {
        esServiceImpl.query();
    }
    
}

EsService.java

public interface EsService {
    void query();
    void save();
    void delete();
}

EsServiceImpl.java

@Service("esServiceImpl")
public class EsServiceImpl implements EsService {
	@Autowired
    private EsDao esDao;

	@Override
	public void query() {
		// TODO Auto-generated method stub
		String queryString = "springboot";//搜索关键字
        QueryStringQueryBuilder builder = new QueryStringQueryBuilder(queryString);
        Iterable<Article> searchResult = esDao.search(builder);
        Iterator<Article> iterator = searchResult.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
		System.out.println("query");
	}

	@Override
	public void save() {
		// TODO Auto-generated method stub
		Author author = new Author();
        author.setId(1L);
        author.setName("mobai");
        author.setRemark("java developer");

        Tutorial tutorial = new Tutorial();
        tutorial.setId(1L);
        tutorial.setName("elastic search");

        Article article = new Article();
        article.setId(1L);
        article.setTitle("springboot integreate elasticsearch");
        article.setAbstracts("springboot integreate elasticsearch is very easy");
        article.setTutorial(tutorial);
        article.setAuthor(author);
        article.setContent("elasticsearch based on lucene,"
                + "spring-data-elastichsearch based on elaticsearch"
                + ",this tutorial tell you how to integrete springboot with spring-data-elasticsearch");
        article.setPostTime(new Date());
        article.setClickCount(1L);
		esDao.save(article);
	}

	@Override
	public void delete() {
		// TODO Auto-generated method stub
		System.out.println("delete");
	}

}

4.2  相关问题

       在项目过程中,出现以下问题:

Description:
Field esServiceImpl in com.sshmobai.es.controller.EsController required a bean of type 'com.sshmobai.es.service.EsService' that could not be found.

Action:
Consider defining a bean of type 'com.sshmobai.es.service.EsService' in your configuration

通过网上教程,修改后,访问浏览器时,页面出现以下问题:

Whitelabel Error Page 
This application has no explicit mapping for /error, so you are seeing this as a fallback. 
……
There was an unexpected error (type=Not Found, status=404). 
No message available

通过查阅文档等途径,在这个网址上得到启发:https://www.jianshu.com/p/6c3b456b0511

分别在以下两个类中添加注释:

@Component("esDao")
public interface EsDao extends ElasticsearchRepository<Article, Long> {}
@Service("esServiceImpl")
public class EsServiceImpl implements EsService{……}

4.3  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.sshmobai</groupId>
	<artifactId>ESdemo</artifactId>
	<version>1.0</version>
	<packaging>jar</packaging>

	<name>ESdemo</name>
	<description>Demo project for Spring Boot</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.2.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
	</properties>

	<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-jdbc</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>1.3.2</version>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<scope>runtime</scope>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>


</project>

猜你喜欢

转载自blog.csdn.net/m0_38084243/article/details/80589761