ES-SpringBoot

226 阅读1分钟

引入依赖

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

编写实体

package com.gavin.exer.entity;

import lombok.Data;
import org.springframework.data.elasticsearch.annotations.Document;
@Data
@Document(indexName = "users")
public class User {
    private int id;
    private String username;
    private String password;
    private int age;

    /** getter and setter */
}

编写DAO

package com.gavin.exer.mapper;

import com.gavin.exer.entity.User;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;

public interface UserDao extends ElasticsearchRepository<User, Integer> {
}

编写Controller

package com.gavin.exer.controller;

import com.gavin.exer.entity.User;
import com.gavin.exer.mapper.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {
    @Autowired
    UserDao userDao;

    @PostMapping("/addUser")
    public String addUser(String username, String password, Integer age) {
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setAge(age);
        return String.valueOf(userDao.save(user).getId());// 返回id做验证
    }

    @DeleteMapping("/deleteUser")
    public String deleteUser(Integer id) {
        userDao.deleteById(id);
        return "Success!";
    }

    @PutMapping("/updateUser")
    public String updateUser(Integer id, String username, String password, Integer age) {
        User user = new User();
        user.setId(id);
        user.setUsername(username);
        user.setPassword(password);
        user.setAge(age);
        return String.valueOf(userDao.save(user).getId());// 返回id做验证
    }

    @GetMapping("/getUser")
    public User getUser(Integer id) {
        return userDao.findById(id).get();
    }

    @GetMapping("/getAllUsers")
    public Iterable<User> getAllUsers() {
        return userDao.findAll();
    }
}

postman测试

POST http://localhost:8080/addUser?username="gavin"&password="gavin"&age=10

PUT http://localhost:8080/updateUser?username="gavin"&password="gavin"&age=10&id=1

GET http://localhost:8080/getAllUsers

GET http://localhost:8080/getUser?id=0

参考文章

es springboot:zhuanlan.zhihu.com/p/54384152

es rest http访问:cloud.tencent.com/developer/a…

es http api入门教程:www.yiibai.com/elasticsear…