SpringBoot+Elasticsearch

SpringBoot+Elasticsearch,第1张

概述1. 前言 1.1. 集成方式 Spring Boot中集成Elasticsearch有4种方式: 本文用后面两种方式来分别连接并 *** 作Elasticsearch 1.2. 环境与配置 服务端:elas

1.  前言

1.1.  集成方式

Spring Boot中集成Elasticsearch有4种方式:

REST ClIEntJestSpring DataSpring Data Elasticsearch RepositorIEs

本文用后面两种方式来分别连接并 *** 作Elasticsearch

1.2.  环境与配置

服务端:elasticsearch-6.3.2    1台

客户端:elasticsearch 6.4.1

服务端配置文件:elasticsearch.yml

cluster.name: my-applicationnetwork.host: 192.168.1.134http.port: 9200

/etc/security/limits.conf

cheng soft nofile 65536cheng hard nofile 65536

/etc/sysctl.conf

vm.max_map_count=262144

1.3.  版本

Spring Boot 2.0.5默认的elasticsearch版本很低,这里我们用最新版本6.4.1

如果启动过程中出现

java.lang.NoClassDefFoundError: org/elasticsearch/common/transport/InetSocketTransportAddress

则说明,elasticsearch依赖的jar包版本不一致,统一改成6.4.1即可

另外,Spring Boot 2.0.5依赖的spring-data-elasticsearch版本是3.0.1,需要升级到3.1.0

2.  依赖

<?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</>    groupID>com.cJs.exampleartifactID>cJs-elasticsearch-exampleversion>0.0.1-SNAPSHOTpackaging>jarnamedescription></parent>        >org.springframework.boot>spring-boot-starter-parent>2.0.5.RELEASErelativePath/> <!-- lookup parent from repository -->    propertIEsproject.build.sourceEnCoding>UTF-8project.reporting.outputEnCodingjava.version>1.8>        elasticsearch.version>6.4.1spring.data.elasticsearch.version>3.1.0.RELEASEdependencIEsdependency>            >org.elasticsearch>elasticsearch>${elasticsearch.version}>org.elasticsearch.clIEnt>transport>elasticsearch-rest-clIEnt>org.elasticsearch.plugin>transport-netty4-clIEnt>org.springframework.data>spring-data-elasticsearch>${spring.data.elasticsearch.version}>spring-boot-starter-data-elasticsearch>spring-boot-starter-web>org.projectlombok>lombokoptional>true>spring-boot-starter-testscope>testbuildpluginsplugin>                >spring-boot-maven-plugin>project>

3.  application.propertIEs

spring.data.elasticsearch.cluster-name=my-applicationspring.data.elasticsearch.cluster-nodes=192.168.1.134:9300

也许,大家会疑惑,配置文件中明明写的端口是9200,为何这里配置文件中连接的时候写的端口是9300呢?

因为,配置9200是通过http连接的端口,9300是TCP连接的端口

4.  *** 作

4.1.  使用Spring Data Elasticsearch RepositorIEs *** 作Elasticsearch

首先,定义一个实体类

package com.cJs.example.entity;import lombok.Data; org.springframework.data.annotation.ID; org.springframework.data.elasticsearch.annotations.document; java.io.Serializable;@Data@document(indexname = "commodity")public class commodity implements Serializable {    @ID    private String skuID;     String name;     String category;     Integer price;     String brand;     Integer stock;}

这里定义了commodity实例,表示商品。在Elasticsearch 6.X 版本中,不建议使用type,而且在7.X版本中将会彻底废弃type,所以此处我只指定了indexname,没有指定type。这里,一个commodity代表一个商品,同时代表一条索引记录。

类比关系型数据库的话,Index相当于表,document相当于记录

 

然后,需要自己定义一个接口,并继承ElasticsearchRepository

 com.cJs.example.dao; com.cJs.example.entity.commodity; org.springframework.data.elasticsearch.repository.ElasticsearchRepository; org.springframework.stereotype.Repository;@Repositoryinterface commodityRepository extends ElasticsearchRepository<commodity,String> {}

这里的Repository相当于DAO, *** 作MysqL还是elasticsearch都是一样的

接下来,定义service接口

 com.cJs.example.service; org.springframework.data.domain.Page; java.util.List;interface commodityService {    long count();    commodity save(commodity commodity);    voID delete(commodity commodity);    Iterable<commodity> getAll();    List<commodity> getByname(String name);    Page<commodity> pagequery(Integer pageNo,Integer pageSize,String kw);}

实现类

 com.cJs.example.service.impl; com.cJs.example.dao.commodityRepository; com.cJs.example.service.commodityService; org.elasticsearch.index.query.MatchqueryBuilder; org.elasticsearch.index.query.queryBuilders; org.springframework.beans.factory.annotation.autowired; org.springframework.data.domain.Page; org.springframework.data.domain.PageRequest; org.springframework.data.elasticsearch.core.query.NativeSearchqueryBuilder; org.springframework.data.elasticsearch.core.query.Searchquery; org.springframework.stereotype.Service; java.util.ArrayList; java.util.List;@Serviceclass commodityServiceImpl  commodityService {    @autowired     commodityRepository commodityRepository;    @OverrIDe     count() {        return commodityRepository.count();    }    @OverrIDe    public commodity save(commodity commodity) {         commodityRepository.save(commodity);    }    @OverrIDe     delete(commodity commodity) {        commodityRepository.delete(commodity);//        commodityRepository.deleteByID(commodity.getSkuID());    }    @OverrIDe    public Iterable<commodity> getAll() {         commodityRepository.findAll();    }    @OverrIDe    public List<commodity> getByname(String name) {        List<commodity> List = new ArrayList<>();        MatchqueryBuilder matchqueryBuilder = new MatchqueryBuilder("name",name);        Iterable<commodity> iterable = commodityRepository.search(matchqueryBuilder);        iterable.forEach(e->List.add(e));         List;    }    @OverrIDe    public Page<commodity>new NativeSearchqueryBuilder()                .withquery(queryBuilders.matchPhrasequery("name" commodityRepository.search(searchquery);    }}

在这个Service中演示了增删查改 *** 作,还有分页查询

最后,写一个测试类测试其中的方法

 com.cJs.example; org.junit.Test; org.junit.runner.RunWith; org.springframework.boot.test.context.SpringBoottest; org.springframework.test.context.junit4.springrunner; java.util.List;@RunWith(springrunner.class)@SpringBoottest CJsElasticsearchExampleApplicationTests {    @autowired     commodityService commodityService;    @Test     contextLoads() {        System.out.println(commodityService.count());    }    @Test     testInsert() {        commodity commodity =  commodity();        commodity.setSkuID("1501009001");        commodity.setname("原味切片面包(10片装)");        commodity.setcategory("101");        commodity.setPrice(880);        commodity.setBrand("良品铺子");        commodityService.save(commodity);        commodity =  commodity();        commodity.setSkuID("1501009002");        commodity.setname("原味切片面包(6片装)");        commodity.setPrice(680 commodity();        commodity.setSkuID("1501009004");        commodity.setname("元气吐司850g");        commodity.setPrice(120);        commodity.setBrand("百草味");        commodityService.save(commodity);    }    @Test     testDelete() {        commodity commodity = );        commodityService.delete(commodity);    }    @Test     testGetAll() {        Iterable<commodity> iterable = commodityService.getAll();        iterable.forEach(e->System.out.println(e.toString()));    }    @Test     testGetByname() {        List<commodity> List = commodityService.getByname("面包");        System.out.println(List);    }    @Test     testPage() {        Page<commodity> page = commodityService.pagequery(0,10,"切片");        System.out.println(page.getTotalPages());        System.out.println(page.getNumber());        System.out.println(page.getContent());    }}

以上,便是使用Elasticsearch RepositorIEs的方式

4.2.  使用ElasticsearchTemplate方式 *** 作Elasticsearch

 org.springframework.data.elasticsearch.core.ElasticsearchTemplate;import org.springframework.data.elasticsearch.core.query.*; ElasticsearchTemplateTest {    @autowired     ElasticsearchTemplate elasticsearchTemplate;    @Test     commodity();        commodity.setSkuID("1501009005");        commodity.setname("葡萄吐司面包(10片装)");        commodity.setPrice(160);        Indexquery indexquery =  IndexqueryBuilder().withObject(commodity).build();        elasticsearchTemplate.index(indexquery);    }    @Test     testquery() {        Searchquery searchquery =  NativeSearchqueryBuilder()                .withquery(queryBuilders.matchquery("name","吐司"))                .build();        List<commodity> List = elasticsearchTemplate.queryForList(searchquery,commodity.);        System.out.println(List);    }}

ElasticsearchTemplate是自动配置的

 

5.  演示

 

6. 工程结构

 

 

7.  参考

https://docs.spring.io/spring-data/elasticsearch/docs/3.1.0.RELEASE/reference/html/#repositories.query-methods.details

 

总结

以上是内存溢出为你收集整理的SpringBoot+Elasticsearch全部内容,希望文章能够帮你解决SpringBoot+Elasticsearch所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1216995.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-05
下一篇 2022-06-05

发表评论

登录后才能评论

评论列表(0条)

保存