elasticsearch入门(四)与springboot整合

ubuntu安装elasticsearch
基本用法
高级查询【上】
高级查询【下】
与springboot整合
整合mysql和thymeleaf

前言:

springboot版本:release 2.1.3
elasticsearch版本:5.6.16

关于elasticsearch的安装和使用,可以看我前面的博客。
参考链接:
https://blog.csdn.net/chengyuqiang/article/details/86135795
1.pom.xml

<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-elasticsearch -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
        </dependency>

2.实体类(这里使用了lombok的data注解):

package com.lingfei.admin.entity;

import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;

/**
 * @author www.xyjz123.xyz
 * @date 2019/3/31 0:17
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
@Document(indexName = "notice", type = "doc")
public class Notice {

    @Id
    private String id;

    @Field(type = FieldType.Text)
    private String title;

    @Field(type = FieldType.Keyword)
    private String author;

    @Field(type = FieldType.Date)
    private String originCreateTime;

    @Field(type = FieldType.Integer)
    private Integer readCount;

}

3、DAO类

package com.lingfei.admin.mapper;

import com.lingfei.admin.entity.Notice;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.stereotype.Component;

/**
 * @author www.xyjz123.xyz
 * @date 2019/3/31 0:19
 */
@Component
public interface NoticeMapper extends ElasticsearchRepository<Notice, String>{

    /**
     * 根据作者查找并分页
     * @param author
     * @param pageable
     * @return
     */
    Page<Notice> findByAuthor(String author, Pageable pageable);

    /**
     * 根据标题查找并分页
     * @param title
     * @param pageable
     * @return
     */
    Page<Notice> findByTitle(String title, Pageable pageable);
}

4、’service接口类

package com.lingfei.admin.service;

import com.lingfei.admin.entity.Notice;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
 * @author www.xyjz123.xyz
 * @date 2019/3/31 10:51
 */
@Service
public interface NoticeService {
    Optional<Notice> findById(String id);

    Notice save(Notice blog);

    void delete(Notice blog);

    Optional<Notice> findOne(String id);

    List<Notice> findAll();

    Page<Notice> findByAuthor(String author, PageRequest pageRequest);

    Page<Notice> findByTitle(String title, PageRequest pageRequest);
}

5、service实现类:

package com.lingfei.admin.service.impl;

import com.lingfei.admin.entity.Notice;
import com.lingfei.admin.mapper.NoticeMapper;
import com.lingfei.admin.service.NoticeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
 * @author www.xyjz123.xyz
 * @date 2019/3/31 10:33
 */
@Service("noticeService")
public class NoticeServiceImpl implements NoticeService {

    @Autowired
    @Qualifier("noticeMapper")
    private NoticeMapper noticeMapper;


    @Override
    public Optional<Notice> findById(String id) {
        //CrudRepository中的方法
        return noticeMapper.findById(id);
    }

    @Override
    public Notice save(Notice blog) {
        return noticeMapper.save(blog);
    }

    @Override
    public void delete(Notice blog) {
        noticeMapper.delete(blog);
    }

    @Override
    public Optional<Notice> findOne(String id) {
        return noticeMapper.findById(id);
    }

    @Override
    public List<Notice> findAll() {
        return (List<Notice>) noticeMapper.findAll();
    }

    @Override
    public Page<Notice> findByAuthor(String author, PageRequest pageRequest) {
        return noticeMapper.findByAuthor(author,pageRequest);
    }

    @Override
    public Page<Notice> findByTitle(String title, PageRequest pageRequest) {
        return noticeMapper.findByTitle(title,pageRequest);
    }

}

6、返回消息的工具类:

package com.lingfei.admin.utils;

import java.util.List;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Data;

/**
 * 自定义响应数据结构
 * 门户接受此类数据后需要使用本类的方法转换成对于的数据类型格式(类,或者list)
 * 其他自行处理
 * 200:表示成功
 * 500:表示错误,错误信息在msg字段中
 * 501:bean验证错误,不管多少个错误都以map形式返回
 * 502:拦截器拦截到用户token出错
 * 555:异常抛出信息
 *
 * @author www.xyj123.xyz
 * @date 2019/3/30 13:57
 *  
 */
@Data
public class JsonResult {

    /**
    *定义jackson对象
     */
    private static final ObjectMapper MAPPER = new ObjectMapper();

    /**
     * 响应业务状态
     */
    private Integer status;

    /**
     * 响应消息
     */
    private String msg;

    /**
     * 响应中的数据
     */
    private Object data;
    private String ok;

    public static JsonResult build(Integer status, String msg, Object data) {
        return new JsonResult(data);
    }

    public static JsonResult ok(Object data) {
        return new JsonResult(data);
    }

    public static JsonResult ok() {
        Object msg = "OK";
        return new JsonResult(msg);
    }

    public static JsonResult errorMsg(String msg) {
        return new JsonResult(msg);
    }

    public static JsonResult errorMap(Object data) {
        return new JsonResult(data);
    }

    public static JsonResult errorTokenMsg(String msg) {
        return new JsonResult(null);
    }

    public static JsonResult errorException(String msg) {
        return new JsonResult(null);
    }

    public JsonResult(String msg) {
        this.status = 500;
        this.msg = msg;
        this.data = null;
    }

    public JsonResult(Object data) {
        this.status = 200;
        this.msg = "OK";
        this.data = data;
    }

    public Boolean isOK() {
        return this.status == 200;
    }

    /**
     * @param jsonData
     * @param clazz
     * @return
     * @Description: 将json结果集转化为LeeJSONResult对象
     * 需要转换的对象是一个类
     */
    public static JsonResult formatToPojo(String jsonData, Class<?> clazz) {
        try {
            if (clazz == null) {
                return MAPPER.readValue(jsonData, JsonResult.class);
            }
            JsonNode jsonNode = MAPPER.readTree(jsonData);
            JsonNode data = jsonNode.get("data");
            Object obj = null;
            if (clazz != null) {
                if (data.isObject()) {
                    obj = MAPPER.readValue(data.traverse(), clazz);
                } else if (data.isTextual()) {
                    obj = MAPPER.readValue(data.asText(), clazz);
                }
            }
            return build(jsonNode.get("status").intValue(), jsonNode.get("msg").asText(), obj);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * @param json
     * @return
     * @Description: 没有object对象的转化
     */
    public static JsonResult format(String json) {
        try {
            return MAPPER.readValue(json, JsonResult.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * @param jsonData
     * @param clazz
     * @return
     * @Description: Object是集合转化
     * 需要转换的对象是一个list
     */
    public static JsonResult formatToList(String jsonData, Class<?> clazz) {
        try {
            JsonNode jsonNode = MAPPER.readTree(jsonData);
            JsonNode data = jsonNode.get("data");
            Object obj = null;
            if (data.isArray() && data.size() > 0) {
                obj = MAPPER.readValue(data.traverse(),
                        MAPPER.getTypeFactory().constructCollectionType(List.class, clazz));
            }
            return build(jsonNode.get("status").intValue(), jsonNode.get("msg").asText(), obj);
        } catch (Exception e) {
            return null;
        }
    }
}

7、control类:

package com.lingfei.admin.control;

import com.lingfei.admin.entity.Notice;
import com.lingfei.admin.service.NoticeService;
import com.lingfei.admin.utils.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;

/**
 * @author www.xyjz123.xyz
 * @date 2019/3/30 21:12
 */
@RestController
@RequestMapping("es")
public class NoticeControl {

    @Autowired
    private NoticeService noticeService;

    @GetMapping("/book/{id}")
    @ResponseBody
    public JsonResult getBookById(@PathVariable String id){
        Optional<Notice> opt =noticeService.findById(id);
        Notice book=opt.get();
        System.out.println(book);
        return JsonResult.ok(book);
    }

    @GetMapping("/save")
    @ResponseBody
    public JsonResult saveNotice(){
        Notice book=new Notice("1","ES入门","熊义杰","2019-03-31",200);
        if(book == null){
            return JsonResult.errorMsg("增加失败");
        }
        noticeService.save(book);
        return JsonResult.ok();
    }
}

我使用的是postman做http请求:
在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值