springboot项目中使用elasticsearch文件数据库开发应用
1、安装并启动elasticsearch后,新建springboot项目
2、创建项目,并导入 elasticsearch jar包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
3、properties文件中添加配置项
spring.data.elasticsearch.client.reactive.endpoints=127.0.0.1:9200spring.data.elasticsearch.client.reactive.connection-timeout=100000
spring.data.elasticsearch.client.reactive.socket-timeout=5000
spring.data.elasticsearch.client.reactive.use-ssl=false
spring.data.elasticsearch.repositories.enabled=true
spring.elasticsearch.rest.uris=${spring.data.elasticsearch.client.reactive.endpoints}
spring.elasticsearch.rest.connection-timeout=${spring.data.elasticsearch.client.reactive.connection-timeout}
spring.elasticsearch.rest.read-timeout=${spring.data.elasticsearch.client.reactive.socket-timeout}
4、创建数据实体类
@ApiModel(description = "Goods实体")@Data
@EqualsAndHashCode(callSuper = false)
@JsonInclude(JsonInclude.Include.NON_NULL)
@Accessors(chain = true)
@Document(indexName = "big_data_center_goods", type = "goods", shards = 1, replicas = 0)
public class Goods implements Serializable {
@ApiModelProperty(value = "主键ID", example = "ce2e7aaf4ecd45e59967668d06441dc9")
@Id
private String id;
@ApiModelProperty(value = "店铺编码", example = "123456")
private String shopCode;
@ApiModelProperty(value = "商品名称", example = "商品名称")
private String goodsName;
@ApiModelProperty(value = "商品价格", example = "123.1")
private BigDecimal price;
@ApiModelProperty(value = "商品描述", example = "商品描述")
private String desc;
@ApiModelProperty(value = "创建时间", example = "2020-03-29 15:52:11")
private String createTime;
}
5、创建Dao类
@Repositorypublic interface GoodsRepository extends ElasticsearchRepository<Goods, String> {
@Query("{"query":{"match":{"shopName":"?0"}}}")
Page<Goods> findByGoodsName(String shopName, Pageable pageable);
@Query("{"query":{"match":{"shopCode":"?0"}}}")
Page<Goods> findByShopCode(String shopCode, Pageable pageable);
}
6、创建service类
public interface IGoodsService { Optional<Goods> findById(String id);
Goods save(Goods blog);
void delete(Goods blog);
Goods update(Goods blog);
Optional<Goods> findOne(String id);
Iterable<Goods> findAll();
Page<Goods> findByShopName(String shopName, Pageable pageable);
Page<Goods> findByShopCode(String shopCode, Pageable pageable);
}
@Slf4j@Service
public class GoodsServiceImpl implements IGoodsService {
@Autowired
@Qualifier("goodsRepository")
private GoodsRepository goodsRepository;
@Override
public Optional<Goods> findById(String id) {
Optional<Goods> optionalShop = null;
try {
optionalShop = goodsRepository.findById(id);
} catch (Exception e) {
log.error(">>>>>>>>>>>>>>>>>>>>>>", e);
}
return optionalShop;
}
@Override
public Goods save(Goods blog) {
Goods shop = null;
try {
shop = goodsRepository.save(blog);
} catch (Exception e) {
log.error(">>>>>>>>>>>>>>>>>>>>>>", e);
}
return shop;
}
@Override
public void delete(Goods blog) {
try {
goodsRepository.delete(blog);
} catch (Exception e) {
log.error(">>>>>>>>>>>>>>>>>>>>>>", e);
}
}
@Override
public Goods update(Goods blog) {
Goods tmp = null;
try {
if (StringUtils.isBlank(blog.getId())) {
return null;
}
Optional<Goods> optional = findById(blog.getId());
if (optional != null) {
tmp = optional.get();
}
if (tmp != null) {
BeanUtils.copyProperties(blog, tmp);
goodsRepository.save(tmp);
}
} catch (Exception e) {
log.error(">>>>>>>>>>>>>>>>>>>>>>", e);
}
return tmp;
}
@Override
public Optional<Goods> findOne(String id) {
Optional<Goods> optionalShop = null;
try {
optionalShop = goodsRepository.findById(id);
} catch (Exception e) {
log.error(">>>>>>>>>>>>>>>>>>>>>>", e);
}
return optionalShop;
}
@Override
public Iterable<Goods> findAll() {
Iterable<Goods> shops = null;
try {
shops = goodsRepository.findAll();
} catch (Exception e) {
log.error(">>>>>>>>>>>>>>>>>>>>>>", e);
}
return shops;
}
@Override
public Page<Goods> findByShopName(String shopName, Pageable pageable) {
Page<Goods> shopPage = null;
try {
shopPage = goodsRepository.findByGoodsName(shopName, pageable);
} catch (Exception e) {
log.error(">>>>>>>>>>>>>>>>>>>>>>", e);
}
return shopPage;
}
@Override
public Page<Goods> findByShopCode(String shopCode, Pageable pageable) {
Page<Goods> shopPage = null;
try {
shopPage = goodsRepository.findByShopCode(shopCode, pageable);
} catch (Exception e) {
log.error(">>>>>>>>>>>>>>>>>>>>>>", e);
}
return shopPage;
}
}
7、创建Action 接口类
@Api(value = "商品接口")@Slf4j
@RestController
@RequestMapping("/goods")
public class GoodsController {
@Autowired
IGoodsService goodsService;
@ApiOperation(value = "根据id查询商品信息", notes="根据id查询商品信息", httpMethod = "GET")
@ApiImplicitParam(name = "id", value = "商品id", required = true, dataType = "String", paramType = "query", example = "d63b7330b7fd443380326d78ad3966f6")
@GetMapping(value = "/findById")
public ResponseEntity<Optional<Goods>> findById(@RequestParam("id") String id) {
Optional<Goods> data = goodsService.findById(id);
return new ResponseEntity<>(data, HttpStatus.OK);
}
@ApiOperation(value = "根据店铺编码查询商品信息", notes="根据店铺编码查询商品信息", httpMethod = "GET")
@ApiImplicitParams({
@ApiImplicitParam(name = "shopCode", value = "编码", required = true, dataType = "String", paramType = "query", example = "000001"),
@ApiImplicitParam(name = "page", value = "页码", required = true, dataType = "int", paramType = "query", example = "1"),
@ApiImplicitParam(name = "size", value = "每页条数", required = true, dataType = "int", paramType = "query", example = "10")
})
@GetMapping(value = "/findByShopCode")
public ResponseEntity<Page<Goods>> findByShopCode(@RequestParam("shopCode") String shopCode,
@RequestParam("page") int page, @RequestParam("size") int size) {
Pageable pageable = PageRequest.of(page, size, Sort.by("createTime"));
Page<Goods> data = goodsService.findByShopCode(shopCode, pageable);
return new ResponseEntity<>(data, HttpStatus.OK);
}
@ApiOperation(value = "新增商品信息", notes="新增商品信息", httpMethod = "POST")
@ApiImplicitParams({
@ApiImplicitParam(name = "goodsName", value = "商品名称", required = true, dataType = "String", paramType = "query", example = "商品名称"),
@ApiImplicitParam(name = "shopCode", value = "店铺编码", required = true, dataType = "String", paramType = "query", example = "000001"),
@ApiImplicitParam(name = "price", value = "售价", required = true, dataType = "int", paramType = "query", example = "10.5"),
@ApiImplicitParam(name = "desc", value = "描述", required = true, dataType = "String", paramType = "query", example = "描述")
})
@PostMapping(value = "/createGoods", produces = {"application/json"}, consumes = {"application/json"})
public ResponseEntity<Goods> createGoods(@RequestBody Goods goods) {
String id = UUID.randomUUID().toString().replace("-", "");
String createTime = DateUtil.date2Str(new Date());
goods.setId(id);
goods.setCreateTime(createTime);
Goods data = goodsService.save(goods);
return new ResponseEntity<>(data, HttpStatus.OK);
}
}
8、浏览器打开 http://localhost:8080/swagger-ui.html,测试接口,结果如下
9、简单操作工具类
@Componentpublic class EsRestClientUtil {
private static RestHighLevelClient client;
@Autowired
public EsRestClientUtil(RestHighLevelClient client) {
this.client = client;
}
public static IndexResponse save(String index, String type, String id, Map<String, Object> source) throws IOException {
IndexRequest indexRequest = new IndexRequest(index, type, id);
indexRequest.source(source);
return client.index(indexRequest, RequestOptions.DEFAULT);
}
public static IndexResponse save(String index, String type, Map<String, Object> source) throws IOException {
String id = null;
if (source.containsKey("id")) {
Object idObj = source.get("id");
id = idObj == null? UUID.randomUUID().toString().replace("-", ""): String.valueOf(idObj);
}
IndexRequest indexRequest = new IndexRequest(index, type, id);
indexRequest.source(source);
return client.index(indexRequest, RequestOptions.DEFAULT);
}
public static int saveBatch(String index, String type, List<Map<String, Object>> sourceList) throws IOException {
int count = 0;
if (!CollectionUtils.isEmpty(sourceList)) {
String id = null;
for (Map<String, Object> source : sourceList) {
id = UUID.randomUUID().toString().replace("-", "");
IndexRequest indexRequest = new IndexRequest(index, type, id);
indexRequest.source(source);
client.index(indexRequest, RequestOptions.DEFAULT);
}
}
return count;
}
public static UpdateResponse update(String index, String type, String id, Map<String, Object> source) throws IOException {
UpdateRequest updateRequest = new UpdateRequest(index, type, id);
updateRequest.doc(source);
return client.update(updateRequest, RequestOptions.DEFAULT);
}
public static Object saveOrUpdate(String index, String type, String id, Map<String, Object> source) throws IOException {
Object result = null;
if (exists(index, type, id)) {
result = update(index, type, id, source);
} else {
result = save(index, type, id, source);
}
return result;
}
public static boolean exists(String index) throws IOException {
GetRequest getRequest = new GetRequest(index);
getRequest.type();
return client.exists(getRequest, RequestOptions.DEFAULT);
}
public static boolean exists(String index, String type) throws IOException {
GetRequest getRequest = new GetRequest(index);
getRequest.type(type);
return client.exists(getRequest, RequestOptions.DEFAULT);
}
public static boolean exists(String index, String type, String id) throws IOException {
GetRequest getRequest = new GetRequest(index, type, id);
return client.exists(getRequest, RequestOptions.DEFAULT);
}
public static GetResponse getById(String index, String type, String id) throws IOException {
GetRequest getRequest = new GetRequest(index, type, id);
return client.get(getRequest, RequestOptions.DEFAULT);
}
}
源码示例:https://gitee.com/lion123/springboot-elasticsearch-demo
以上是 springboot项目中使用elasticsearch文件数据库开发应用 的全部内容, 来源链接: utcz.com/z/514895.html