Spring Boot整合Elasticsearch

2019-11-21   250 次阅读


安装elasticsearch

1. 下载

下载:https://www.elastic.co/cn/downloads/elasticsearch

版本:我使用的是最新版(7.4.2)

2. 在Linux下安装&启动

创建elasticsearch用户和组

groupadd es
useradd es -g es -p es

解压

tar -zxvf elasticsearch-7.4.2-linux-x86_64.tar.gz -C /home/es/

进入解压后的目录,给es用户授权

cd /home/es/

chown -R es:es elasticsearch-7.4.2/

修改默认jvm内存大小,因为是测试,不需要很大,所以适当修改就好,不修改如果你的机器内存不够会抛出一个错误:

Java HotSpot(TM) 64-Bit Server VM warning: INFO: os::commit_memory(0x00000000c5330000, 986513408, 0) failed; error='Cannot allocate memory' (errno=12)

修改默jvm配置

cd elasticsearch-7.4.2/config/

vim jvm.options

# 修改如下配置
-Xms256m
-Xmx512m

启动

cd ../

# 切换为es用户
su es

bin/elasticsearch

启动的时候会有这样一个提示:意思就是后续将支持Java11,不过也可以正常启动

future versions of Elasticsearch will require Java 11; your Java version from [/usr/local/jdk/jre] does not meet this requirement

访问

# 使用curl访问
curl http://localhost:9200

{
  "name" : "VM_80_178_centos",
  "cluster_name" : "elasticsearch",
  "cluster_uuid" : "mKL-m0knTVS8N78rRdvEEQ",
  "version" : {
    "number" : "7.4.2",
    "build_flavor" : "default",
    "build_type" : "tar",
    "build_hash" : "2f90bbf7b93631e52bafb59b3b049cb44ec25e96",
    "build_date" : "2019-10-28T20:40:44.881551Z",
    "build_snapshot" : false,
    "lucene_version" : "8.2.0",
    "minimum_wire_compatibility_version" : "6.8.0",
    "minimum_index_compatibility_version" : "6.0.0-beta1"
  },
  "tagline" : "You Know, for Search"
}

外网访问

configelasticsearch.yml中新增如下配置,重启即可:

network.host: 0.0.0.0

# 更改为开发模式
discovery.type: single-node

安装可视化插件

需要安装nodejs和npm,至于怎么安装百度吧,安装完成后,访问http://ip:9100

git clone https://github.com/mobz/elasticsearch-head.git

cd elasticsearch-head

npm install

Spring Boot整合elasticsearch

  1. 初始化一个SpringBoot项目

  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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.2.1.RELEASE</version>
            <relativePath/> <!-- lookup parent from repository -->
        </parent>
        <groupId>com.dbnewyouth</groupId>
        <artifactId>springboot-elasticsearh</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <name>springboot-elasticsearh</name>
        <description>springboot-elasticsearh</description>
    
        <properties>
            <java.version>1.8</java.version>
        </properties>
    
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter</artifactId>
            </dependency>
            <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>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-devtools</artifactId>
                <scope>runtime</scope>
            </dependency>
    
        </dependencies>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
            <resources>
                <resource>
                    <directory>src/main/java</directory>
                    <includes>
                        <include>**/*.properties</include>
                        <include>**/*.xml</include>
                    </includes>
                    <filtering>true</filtering>
                </resource>
                <resource>
                    <directory>src/main/resources</directory>
                    <filtering>true</filtering>
                </resource>
            </resources>
        </build>
    
    </project>
    
    
    
  3. 配置文件application.yaml

    server:
      port: 8080
    
    spring:
      data:
        elasticsearch:
          # 9200是http的端口,9300是java调用的端口
    
          cluster-nodes: 123.207.253.50:9300
          cluster-name: elasticsearch
          local: false
          repositories:
            enabled: true
    
    
  4. 新建User实体类

    需要注意,indexNametype的值必须小写!

    @Document(indexName = "userindex", type = "user")
    public class User implements Serializable {
    
        private static final long serialVersionUID = 1L;
    
        private Long id;
        private String name;
        private Integer age;
        private String sex;
        private String address;
        private String description;
        private Date createTime;
    
        // Getter和Setter方法省略
    
    }
    
    
  5. 新建dao接口,继承ElasticsearchRepository

    public interface UserDao extends ElasticsearchRepository<User, Long> {
    }
    
    
  6. 新建业务层IUserService接口和实现类UserServiceImpl

    新建IUserService接口

    public interface IUserService {    public boolean insert(User user);    public List search(String searchContent);}
    
    

    新建UserServiceImpl实现类

    @Service("userService")
    public class UserServiceImpl implements IUserService {
    
        @Autowired
        private UserDao userDao;
    
        @Override
        public boolean insert(User user) {
            try {
                userDao.save(user);
                return true;
            }catch (Exception e){
                e.printStackTrace();
            }
            return false;
        }
    
        @Override
        public List<User> search(String searchContent) {
            QueryStringQueryBuilder builder = new QueryStringQueryBuilder(searchContent);
            Iterable<User> search = userDao.search(builder);
            if(search == null){
                return null;
            }
            Iterator<User> iterator = search.iterator();
            List<User> list = new ArrayList<>();
            while (iterator.hasNext()){
                list.add(iterator.next());
            }
            return list;
        }
    }
    
    
  7. 新建Result统一返回类,为了方便统一返回结果

    public class Result implements Serializable {
    
        private static final long serialVersionUID = 1L;
    
        private Integer code;
        private String message;
        private Object data;
    
        public Result(Integer code, String message) {
            this.code = code;
            this.message = message;
        }
    
        public Result(Integer code, String message, Object data) {
            this.code = code;
            this.message = message;
            this.data = data;
        }
    
        // Getter和Setter方法省略
    
    }
    
    
  8. 新建UserController

    @RestController
    @RequestMapping("/user")
    public class UserController {
    
        @Autowired
        private IUserService userService;
    
        @PostMapping("/insert")
        public Result insert(User user) {
            if(user == null){
                return new Result(-1, "参数不能为空");
            }
            if(StringUtils.isEmpty(user.getName())){
                return new Result(-1, "姓名不能为空");
            }
            user.setCreateTime(new Date());
            boolean insertStatus = userService.insert(user);
            if(insertStatus){
                return new Result(200, "插入成功");
            }
            return new Result(-1, "插入失败");
        }
    
        @GetMapping("/search")
        public Result search(String searchContent){
            List<User> list = userService.search(searchContent);
            return new Result(200, "查询成功", list);
        }
    }
    
    
  9. 运行SpringbootElasticsearhApplication启动项目即可测试

测试效果,调用Api

测试插入接口

测试查询接口

姓名查询

根据性别或者描述查询

elasticsearch图形化界面

Q.E.D.

知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议

让人非我弱,得志莫离群