rev:lucene

This commit is contained in:
2024-01-08 09:56:55 +08:00
parent 530275d651
commit 9b97d45a5f
45 changed files with 606 additions and 1197 deletions

View File

@@ -261,7 +261,6 @@ public class HailiangEngravingInDeviceDriver extends AbstractOpcDeviceDriver imp
if (mode != last_mode) {
feedDeviceStatusFlag = false;
logServer.deviceExecuteLog(this.device_code, "", "", SignalEnum.getNameByCode("mode") + SignalEnum.getDescByCode("mode") +""+ last_mode + "->" + mode);
lucene.deviceExecuteLog(new LuceneLogDto(this.device_code, ItemProtocol.item_mode, mode, last_mode));
}
if (gd_move != last_gd_move) {
logServer.deviceExecuteLog(this.device_code, "", "", SignalEnum.getNameByCode("move") + SignalEnum.getDescByCode("move") +""+ last_gd_move + "->" + gd_move);

View File

@@ -3,10 +3,12 @@ package org.nl.acs.opc;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.nl.acs.udw.UnifiedDataAccessor;
import org.nl.acs.udw.UnifiedDataAccessorFactory;
import org.nl.acs.udw.UnifiedDataAppService;
import org.nl.modules.lucene.enums.LogTypeEnum;
import org.nl.modules.lucene.service.LuceneExecuteLogService;
import org.nl.modules.lucene.service.dto.LuceneLogDto;
import org.nl.modules.wql.util.SpringContextHolder;
@@ -410,8 +412,9 @@ public class DeviceOpcProtocolRunable implements Runnable, DataCallback, ServerC
}
private void logItemChanged(String itemId, UnifiedDataAccessor accessor_value, Object value, OpcItemDto itemDto) {
LuceneExecuteLogService lucene = SpringContextHolder.getBean(LuceneExecuteLogService.class);
Object his = accessor_value.getValue(itemId);
itemDto.setHis_item_value(his);
itemDto.setItem_value(value);
List<String> relate_items = itemDto.getRelate_items();
if (relate_items != null && !relate_items.isEmpty()) {
StringBuilder sb = new StringBuilder();
@@ -422,14 +425,22 @@ public class DeviceOpcProtocolRunable implements Runnable, DataCallback, ServerC
Object obj = accessor_value.getValue(relate);
sb.append("key:" + relate + "value:" + obj + ";");
}
// log.warn("设备:{}信号{}变更从{}->{};信号快照:{}", new Object[]{itemDto.getDevice_code(), itemId, his, value, sb});
if (!itemDto.getItem_code().endsWith("heartbeat")) {
lucene.deviceExecuteLog(new LuceneLogDto(itemDto.getDevice_code(), itemDto.getItem_code().substring(itemDto.getItem_code().lastIndexOf(".")+1), String.valueOf(his), String.valueOf(value)));
if (!itemDto.getItem_code().endsWith("heartbeat") && !itemDto.getItem_code().endsWith("time")) {
// 存在上次点位值为null情况 则不记录日志
LuceneLogDto luceneLogDto = new LuceneLogDto(itemDto.getOpc_server_code(), itemDto.getOpc_plc_code(), itemDto.getDevice_code(), itemDto.getItem_code().substring(itemDto.getItem_code().lastIndexOf(".") + 1),
String.valueOf(itemDto.getHis_item_value()), String.valueOf(itemDto.getItem_value()));
luceneLogDto.setLogType(LogTypeEnum.DEVICE_LOG.getDesc());
log.info("{}", JSON.toJSONString(luceneLogDto));
}
} else {
// log.warn("设备:{}信号{}变更从{}->{};信号快照:{}", new Object[]{itemDto.getDevice_code(), itemId, his, value});
if (!itemDto.getItem_code().endsWith("heartbeat")) {
lucene.deviceExecuteLog(new LuceneLogDto(itemDto.getDevice_code(), itemDto.getItem_code().substring(itemDto.getItem_code().lastIndexOf(".")+1), String.valueOf(his), String.valueOf(value)));
// log.info("设备:{}信号{}变更从{}->{};信号快照:{}", new Object[]{itemDto.getDevice_code(), itemId, his, value});
// 存在上次点位值为null情况 则不记录日志
if (!itemDto.getItem_code().endsWith("heartbeat") && !itemDto.getItem_code().endsWith("time")) {
LuceneLogDto luceneLogDto = new LuceneLogDto(itemDto.getOpc_server_code(), itemDto.getOpc_plc_code(), itemDto.getDevice_code(), itemDto.getItem_code().substring(itemDto.getItem_code().lastIndexOf(".") + 1),
String.valueOf(itemDto.getHis_item_value()), String.valueOf(itemDto.getItem_value()));
luceneLogDto.setLogType(LogTypeEnum.DEVICE_LOG.getDesc());
log.info("{}", JSON.toJSONString(luceneLogDto));
}
}
}

View File

@@ -11,6 +11,7 @@ public class OpcItemDto {
private String opc_plc_code;
private String item_code;
private Object item_value;
private Object his_item_value;
private Boolean need_log = Boolean.valueOf(false);
private List<String> relate_items = new ArrayList();
@@ -86,4 +87,11 @@ public class OpcItemDto {
this.relate_items = relate_items;
}
public Object getHis_item_value() {
return his_item_value;
}
public void setHis_item_value(Object his_item_value) {
this.his_item_value = his_item_value;
}
}

View File

@@ -1,40 +0,0 @@
package org.nl.modules.loki.rest;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.nl.modules.common.annotation.RateLimiter;
import org.nl.modules.loki.service.LokiService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
/**
* @Author: lyd
* @Description: 日志监控
* @Date: 2022-08-15
*/
@RestController
@RequiredArgsConstructor
@Api(tags = "日志监控")
@RequestMapping("/api/loki")
@Slf4j
public class LokiController {
private final LokiService lokiService;
@GetMapping("/labels/values")
@ApiOperation("获取标签")
public ResponseEntity<Object> labelsValues() {
return new ResponseEntity<>(lokiService.getLabelsValues(), HttpStatus.OK);
}
@PostMapping("/logs")
@ApiOperation("获取日志")
@RateLimiter(value = 1, timeout = 300) // 限流
public ResponseEntity<Object> getLogData(@RequestBody JSONObject json) {
return new ResponseEntity<>(lokiService.getLogData(json), HttpStatus.OK);
}
}

View File

@@ -1,25 +0,0 @@
package org.nl.modules.loki.service;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
/**
* @Author: lyd
* @Description: 服务类
* @Date: 2022-08-15
*/
public interface LokiService {
/**
* 获取日志信息
* @param json
* @return
*/
JSONObject getLogData(JSONObject json);
/**
* 获取labels和values树
* @return
*/
JSONArray getLabelsValues();
}

View File

@@ -1,113 +0,0 @@
package org.nl.modules.loki.service.impl;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.RequiredArgsConstructor;
import org.nl.modules.loki.service.LokiService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
/**
* @Author: lyd
* @Description: 实现类
* @Date: 2022-08-15
*/
@Service
@RequiredArgsConstructor
public class LokiServiceImpl implements LokiService {
@Value("${loki.url}")
private String lokiUrl;
@Value("${loki.systemName}")
private String systemName;
@Override
public JSONObject getLogData(JSONObject json) {
String logLabel = "";
String logLabelValue = "";
Long start = 0L;
Long end = 0L;
String text = "";
String limit = "100";
String direction = "backward";
if (json.get("logLabel") != null) logLabel = json.getString("logLabel");
if (json.get("logLabelValue") != null) logLabelValue = json.getString("logLabelValue");
if (json.get("text") != null) text = json.getString("text");
if (json.get("start") != null) start = json.getLong("start");
if (json.get("end") != null) end = json.getLong("end");
if (json.get("limits") != null) limit = json.getString("limits");
if (json.get("direction") != null) direction = json.getString("direction");
/**
* 组织参数
* 纳秒数
* 1660037391880000000
* 1641453208415000000
* http://localhost:3100/loki/api/v1/query_range?query={host="localhost"} |= ``&limit=1500&start=1641453208415000000&end=1660027623419419002
*/
JSONObject parse = null;
String query = lokiUrl + "/query_range?query={system=\"" + systemName + "\", " + logLabel + "=\"" + logLabelValue + "\"} |= `" + text + "`";
String result = "";
if (start==0L) {
result = HttpUtil.get(query + "&limit=" + limit + "&direction=" + direction, CharsetUtil.CHARSET_UTF_8);
} else {
result = HttpUtil.get(query + "&limit=" + limit + "&start=" + start + "&end=" + end + "&direction=" + direction, CharsetUtil.CHARSET_UTF_8);
}
try {
parse = (JSONObject) JSONObject.parse(result);
} catch (Exception e) {
// reslut的值可能为:too many outstanding requests,无法转化成Json
System.out.println("reslut:" + result);
// e.printStackTrace();
}
return parse;
}
/**
* 获取labels和values树
*
* @return
*/
@Override
public JSONArray getLabelsValues() {
/**
* [{
* label:
* value:
* children:[{
* label
* value
* }]
* }]
*/
JSONArray result = new JSONArray();
// 获取所有标签
String labelString = HttpUtil.get(lokiUrl + "/labels", CharsetUtil.CHARSET_UTF_8);
JSONObject parse = (JSONObject) JSONObject.parse(labelString);
JSONArray labels = parse.getJSONArray("data");
for (int i=0; i<labels.size(); i++) {
// 获取标签下的所有值
String valueString = HttpUtil.get(lokiUrl + "/label/" + labels.getString(i) + "/values", CharsetUtil.CHARSET_UTF_8);
JSONObject parse2 = (JSONObject) JSONObject.parse(valueString);
JSONArray values = parse2.getJSONArray("data");
JSONArray children = new JSONArray();
// 组成树形状态 两级
for (int j=0; j<values.size(); j++) {
JSONObject leaf = new JSONObject();
leaf.put("label", values.getString(j));
leaf.put("value", values.getString(j));
children.add(leaf);
}
JSONObject node = new JSONObject();
node.put("label", labels.getString(i));
node.put("value", labels.getString(i));
node.put("children", children);
result.add(node);
}
return result;
}
}

View File

@@ -1,49 +0,0 @@
package org.nl.modules.lucene.common;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.encoder.PatternLayoutEncoder;
import ch.qos.logback.core.rolling.RollingFileAppender;
import ch.qos.logback.core.rolling.TimeBasedRollingPolicy;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.nio.charset.Charset;
public class DynamicLogAppender {
/**
* 通过传入的动态名字,动态设置appender
* @param dynamicName
* @return
*/
public RollingFileAppender getAppender(String oldLogPath,String dynamicName) {
LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
RollingFileAppender appender = new RollingFileAppender();
//appender的name属性
appender.setName(dynamicName);
appender.setContext(context);
//设置文件名
appender.setFile(new File(oldLogPath, dynamicName + "\\" + DateUtil.format(new DateTime(),"yyyy-MM-dd")+".log").getAbsolutePath());
//设置日志文件输出格式
PatternLayoutEncoder encoder = new PatternLayoutEncoder();
encoder.setContext(context);
encoder.setPattern("%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n");
encoder.setCharset(Charset.forName("UTF-8"));
encoder.start();
//设置日志记录器的滚动策略
TimeBasedRollingPolicy policy = new TimeBasedRollingPolicy();
policy.setFileNamePattern(oldLogPath+dynamicName+".%d{yyyy-MM-dd}.log");
policy.setParent(appender); //设置父节点是appender
policy.setContext(context);
policy.start();
//加入下面两个节点
appender.setRollingPolicy(policy);
appender.setEncoder(encoder);
appender.start();
return appender;
}
}

View File

@@ -1,35 +0,0 @@
package org.nl.modules.lucene.common;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.core.rolling.RollingFileAppender;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.Map;
public class DynamicLogger {
String logPath;//日志存储路径
public DynamicLogger(String logPath) {
this.logPath = logPath;
}
//对外暴露日志对象:每次拿的对象从内存里拿,没有再构建
private static Map<String,Logger> container = new HashMap<>();
public Logger getLogger(String dynamicName) {
Logger logger = container.get(dynamicName);
if(logger != null) {
return logger;
}
logger = build(dynamicName);
container.put(dynamicName,logger);
return logger;
}
//构建Logger对象给Logger指定appender
private Logger build(String dynamicName) {
RollingFileAppender runTaskAppender =new DynamicLogAppender().getAppender(this.logPath,dynamicName);
LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
Logger logger = context.getLogger(dynamicName);
logger.addAppender(runTaskAppender);
return logger;
}
}

View File

@@ -1,178 +0,0 @@
package org.nl.modules.lucene.common;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.FileUtils;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.springframework.beans.factory.annotation.Value;
import org.wltea.analyzer.lucene.IKAnalyzer;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.Set;
/**
* lucene索引器
*/
public class Indexer {
/**
* 写索引实例
*/
private IndexWriter writer;
public IndexWriter getWriter() {
return writer;
}
/**
* 构造方法实例化IndexWriter
* @param indexDir
* @throws Exception
*/
public Indexer(String indexDir) throws Exception {
Directory dir = FSDirectory.open(Paths.get(indexDir));
//标准分词器会自动去掉空格啊is a the等单词
// Analyzer analyzer = new StandardAnalyzer();
Analyzer analyzer = new IKAnalyzer();
//将标准分词器配到写索引的配置中
IndexWriterConfig config = new IndexWriterConfig(analyzer);
//实例化写索引对象
writer = new IndexWriter(dir, config);
}
/**
* 索引指定目录下的所有文件
* @param dataDir
* @return
* @throws Exception
*/
public int indexAll(String dataDir) throws Exception {
// 获取该路径下的所有文件
File[] files = new File(dataDir).listFiles();
if (null != files) {
for (File file : files) {
//调用下面的indexFile方法对每个文件进行索引
indexFile(file);
}
}
//返回索引的文件数
// return writer.numDocs();
return writer.numRamDocs();
}
/**
* 索引指定的文件
* @param file
* @throws Exception
*/
private void indexFile(File file) throws Exception {
System.out.println("索引文件的路径:" + file.getCanonicalPath());
//调用下面的getDocument方法获取该文件的document
Document doc = getDocument(file);
//添加索引文档
//Document doc = json2Doc(jsonDoc);
// Document doc = new Document();
// doc.add(new TextField("content", jsonDoc, Field.Store.YES));
Field fieldContent=new TextField("fieldContent", FileUtils.readFileToString(null,"UTF-8"), Field.Store.YES);
//将doc添加到索引中
writer.addDocument(doc);
}
/**
* 获取文档,文档里再设置每个字段,就类似于数据库中的一行记录
* @param file
* @return
* @throws Exception
*/
private Document getDocument(File file) throws Exception {
Document doc = new Document();
//开始添加字段
//添加内容
doc.add(new TextField("contents", new FileReader(file)));
//添加文件名,并把这个字段存到索引文件里
doc.add(new TextField("fileName", file.getName(), Field.Store.YES));
//添加文件路径
doc.add(new TextField("fullPath", file.getCanonicalPath(), Field.Store.YES));
return doc;
}
public Document json2Doc(String strDoc) {
Document doc = new Document();
JSONObject jsonDoc = JSONObject.parseObject(strDoc);
Set<String> keys = jsonDoc.keySet();
for (String key : keys) {
doc.add(new TextField(key, jsonDoc.getString(key), Field.Store.YES));
}
return doc;
}
public void addLogIndex(String msg) throws IOException {
//步骤一创建Directory对象用于指定索引库的位置 RAMDirectory内存
Directory directory = FSDirectory.open(new File("D:\\lucene\\index").toPath());
//步骤二创建一个IndexWriter对象用于写索引
// Analyzer analyzer = new StandardAnalyzer();
IndexWriter indexWriter=new IndexWriter(directory,new IndexWriterConfig(new IKAnalyzer(false)));
// indexWriter.deleteAll();//清理所有索引库
// IndexWriter indexWriter=new IndexWriter(directory,new IndexWriterConfig(new StandardAnalyzer()));
//记录索引开始时间
long startTime = System.currentTimeMillis();
//步骤三:读取磁盘中文件,对应每一个文件创建一个文档对象
Document document = new Document();
// document.add(new TextField("fieldContent", device_id, Field.Store.YES));
document.add(new TextField("fieldContent", msg, Field.Store.YES));
indexWriter.addDocument(document);
//记录索引结束时间
long endTime = System.currentTimeMillis();
System.out.println("建立索引"+ "共耗时" + (endTime-startTime) + "毫秒");
indexWriter.commit();
//步骤八:关闭资源
indexWriter.close();
System.out.println("建立索引成功-----关闭资源");
}
//系统的日志文件路径
@Value("${logging.file.path}")
private String logUrl;
public static void main(String[] args)throws IOException {
//步骤一创建Directory对象用于指定索引库的位置 RAMDirectory内存
Directory directory = FSDirectory.open(new File("D:\\lucene\\index").toPath());
//步骤二创建一个IndexWriter对象用于写索引
// Analyzer analyzer = new StandardAnalyzer();
IndexWriter indexWriter=new IndexWriter(directory,new IndexWriterConfig(new IKAnalyzer(false)));
indexWriter.deleteAll();//清理所有索引库
// IndexWriter indexWriter=new IndexWriter(directory,new IndexWriterConfig(new StandardAnalyzer()));
//记录索引开始时间
long startTime = System.currentTimeMillis();
//步骤三:读取磁盘中文件,对应每一个文件创建一个文档对象
File file=new File("D:\\testlog");
//步骤四:获取文件列表
File[] files = file.listFiles();
for (File item:files) {
BufferedReader bufferedReader = new BufferedReader(new FileReader(item));
String strLine = null;
while(null != (strLine = bufferedReader.readLine())){
Document document = new Document();
// document.add(new Field());
document.add(new TextField("fieldContent", strLine, Field.Store.YES));
indexWriter.addDocument(document);
}
}
//记录索引结束时间
long endTime = System.currentTimeMillis();
System.out.println("建立索引"+ "共耗时" + (endTime-startTime) + "毫秒");
indexWriter.commit();
//步骤八:关闭资源
indexWriter.close();
System.out.println("建立索引成功-----关闭资源");
}
}

View File

@@ -1,66 +0,0 @@
//package org.nl.modules.lucene.common;
//
//import cn.hutool.core.date.DateUtil;
//import org.apache.lucene.index.CorruptIndexException;
//import org.apache.lucene.index.IndexWriter;
//import org.apache.lucene.index.IndexWriterConfig;
//import org.apache.lucene.store.Directory;
//import org.apache.lucene.store.FSDirectory;
//import org.nl.modules.lucene.config.UrlConfig;
//import org.wltea.analyzer.lucene.IKAnalyzer;
//
//import java.io.File;
//import java.io.IOException;
//import java.text.ParseException;
//import java.text.SimpleDateFormat;
//import java.util.Date;
//
//public class LuceneIndexWriter {
// private static volatile IndexWriter indexWriter;
//
// static {
// try {
// Directory directory = FSDirectory.open(new File(UrlConfig.luceneUrl).toPath());
// IndexWriterConfig config = new IndexWriterConfig(new IKAnalyzer());
// indexWriter = new IndexWriter(directory, config);
// } catch (Exception e) {
// e.printStackTrace();
// }
// /**当当前线程结束时自动关闭IndexWriter使用Runtime对象*/
//// Runtime.getRuntime().addShutdownHook(new Thread(){
//// @Override
//// public void run() {
//// try {
//// closeIndexWriter();
//// } catch (Exception e) {
//// e.printStackTrace();
//// }
//// }
//// });
// }
// /**在线程结束时自动关闭IndexWriter*/
// public static IndexWriter getIndexWriter() {
// return indexWriter;
// }
// /**关闭IndexWriter
// * @throws IOException
// * @throws CorruptIndexException */
// public static void closeIndexWriter() throws Exception {
// if(indexWriter != null) {
//// indexWriter.close();
// }
// }
//
// public static void main(String[] args) throws IOException {
// indexWriter.deleteAll();
// }
//
// public static String getDate(String timeString) throws ParseException {
// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX");//时间格式
// Date date = sdf.parse(timeString);
// timeString = DateUtil.format(date, "yyyy-MM-dd HH:mm:ss.SSS");//格式化后的时间
// return timeString;
// }
//
//
//}

View File

@@ -1,85 +0,0 @@
package org.nl.modules.lucene.common;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.nl.acs.AcsConfig;
import org.nl.acs.auto.run.AbstractAutoRunnable;
import org.nl.modules.system.service.ParamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.wltea.analyzer.lucene.IKAnalyzer;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
@Slf4j
@Component
public class LuceneServiceAutoRun extends AbstractAutoRunnable {
@Autowired
private ParamService paramService;
public LuceneServiceAutoRun() {
}
@Override
public String getCode() {
return LuceneServiceAutoRun.class.getSimpleName();
}
@Override
public String getName() {
return "Lucene索引服务";
}
private static volatile IndexWriter indexWriter;
@Override
public void autoRun() throws IOException {
try {
String luceneUrl = paramService.findByCode(AcsConfig.LUCENEURL).getValue();
Directory directory = FSDirectory.open(new File(luceneUrl).toPath());
IndexWriterConfig config = new IndexWriterConfig(new IKAnalyzer());
indexWriter = new IndexWriter(directory, config);
} catch (Exception e) {
log.error("Lucene索引服务出现异常:{}", JSON.toJSONString(e));
if (ObjectUtil.isNotEmpty(indexWriter)) {
indexWriter.close();
}
}
}
/**在线程结束时会自动关闭IndexWriter*/
public static IndexWriter getIndexWriter() {
return indexWriter;
}
@Override
public void stop() {
super.after();
try {
indexWriter.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
indexWriter.deleteAll();
}
public static String getDate(String timeString) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX");//时间格式
Date date = sdf.parse(timeString);
timeString = DateUtil.format(date, "yyyy-MM-dd HH:mm:ss.SSS");//格式化后的时间
return timeString;
}
}

View File

@@ -1,140 +0,0 @@
package org.nl.modules.lucene.common;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.*;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.BytesRef;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
/**
* lucene查询器
*/
@Slf4j
public class Searcher {
public static Map<String, Object> search(String indexDir, String ext,Map whereJson) throws Exception {
//获取要查询的路径,也就是索引所在的位置
Directory dir = FSDirectory.open(Paths.get(indexDir));
IndexReader reader = DirectoryReader.open(dir);
//构建IndexSearcher
IndexSearcher searcher = new IndexSearcher(reader);
//标准分词器会自动去掉空格啊is a the等单词
// Analyzer analyzer = new StandardAnalyzer();
// Analyzer analyzer = new IKAnalyzer(false);
//查询解析器
// QueryParser queryParser = new QueryParser("fieldContent", analyzer);
//记录索引开始时间
long startTime = System.currentTimeMillis();
// 实际上Lucene本身不支持分页。因此我们需要自己进行逻辑分页。我们要准备分页参数
int pageSize = Integer.parseInt(whereJson.get("size").toString());// 每页条数
int pageNum = Integer.parseInt(whereJson.get("page").toString());// 当前页码
int start = pageNum * pageSize;// 当前页的起始条数
int end = start + pageSize;// 当前页的结束条数(不能包含)
TopDocs docs = null;
BooleanQuery.Builder booleanQueryBuilder = new BooleanQuery.Builder();
//时间范围查询
String startDate = (String) whereJson.get("begin_time");
String endDate = (String) whereJson.get("end_time");
Calendar calendar=Calendar.getInstance();
calendar.set(1970, 0, 1);
if (startDate == null){
startDate = DateUtil.format(calendar.getTime(),"yyyy-MM-dd HH:mm:ss.SSS");
}else{
startDate = LuceneServiceAutoRun.getDate(startDate);
}
if (endDate == null){
endDate = DateUtil.format(new DateTime(),"yyyy-MM-dd HH:mm:ss.SSS");
} else {
endDate = LuceneServiceAutoRun.getDate(endDate);
}
TermRangeQuery termRangeQuery = new TermRangeQuery("logTime", new BytesRef(startDate), new BytesRef(endDate), true, true);
booleanQueryBuilder.add(termRangeQuery,BooleanClause.Occur.MUST);
if (whereJson.get("device_code") != null){
Query termQuery = new TermQuery(new Term("device_code", (String) whereJson.get("device_code")));
booleanQueryBuilder.add(termQuery,BooleanClause.Occur.MUST);
}
if (whereJson.get("method") != null){
Query termQuery = new TermQuery(new Term("method", (String) whereJson.get("method")));
booleanQueryBuilder.add(termQuery,BooleanClause.Occur.MUST);
}
if (whereJson.get("status_code") != null){
Query termQuery = new TermQuery(new Term("status_code", (String) whereJson.get("status_code")));
booleanQueryBuilder.add(termQuery,BooleanClause.Occur.MUST);
}
if (whereJson.get("requestparam") != null){
WildcardQuery query = new WildcardQuery(new Term("requestparam", "*"+(String) whereJson.get("requestparam")+"*"));
booleanQueryBuilder.add(query,BooleanClause.Occur.MUST);
}
if (whereJson.get("responseparam") != null){
WildcardQuery query = new WildcardQuery(new Term("responseparam", "*"+(String) whereJson.get("responseparam")+"*"));
booleanQueryBuilder.add(query,BooleanClause.Occur.MUST);
}
if (whereJson.get("blurry") != null) {
WildcardQuery query = new WildcardQuery(new Term("fieldContent", "*"+(String) whereJson.get("blurry")+"*"));
booleanQueryBuilder.add(query, BooleanClause.Occur.MUST);
}
// 创建排序对象,需要排序字段SortField参数字段的名称、字段的类型、是否反转如果是false升序。true降序
Sort sort = new Sort(new SortField("logTime",SortField.Type.LONG,true));
docs = searcher.search(booleanQueryBuilder.build(), end, sort);
// docs = searcher.search(booleanQueryBuilder.build(), end, Sort.INDEXORDER);
//记录索引时间
long endTime = System.currentTimeMillis();
log.info("匹配{}共耗时{}毫秒",booleanQueryBuilder.build(),(endTime-startTime));
log.info("查询到{}条日志文件", docs.totalHits.value);
List<String> list = new ArrayList<>();
ScoreDoc[] scoreDocs = docs.scoreDocs;
if (end > docs.totalHits.value) end = (int) docs.totalHits.value;
JSONArray array = new JSONArray();
for (int i = start; i < end; i++) {
ScoreDoc scoreDoc = scoreDocs[i];
Document doc = reader.document(scoreDoc.doc);
JSONObject object = new JSONObject();
object.put("content",doc.get("fieldContent"));
object.put("device_code",doc.get("device_code"));
object.put("logTime",doc.get("logTime"));
object.put("method",doc.get("method"));
object.put("status_code",doc.get("status_code"));
object.put("requestparam",doc.get("requestparam"));
object.put("responseparam",doc.get("responseparam"));
if(doc.get("fieldContent") != null) {
array.add(object);
}
}
for(Object logDto:array){
log.info(logDto.toString());
}
reader.close();
JSONObject jo = new JSONObject();
jo.put("content", array);
jo.put("totalElements", docs.totalHits.value);
return jo;
}
public static void main(String[] args) {
String indexDir = "D:\\lucene\\index";
//查询这个字符串
String q = "07.832";
Map whereJson = null;
try {
search(indexDir, q,whereJson);
} catch (Exception e) {
e.printStackTrace();
}
}
}

View File

@@ -0,0 +1,43 @@
package org.nl.modules.lucene.config;
/**
* @author ldjun
* @version 1.0
* @date 2023年08月24日 13:00
* @desc desc
*/
import ch.qos.logback.classic.spi.ILoggingEvent;
import cn.hutool.core.util.IdUtil;
import com.yomahub.tlog.core.context.AspectLogContext;
import com.yomahub.tlog.core.enhance.logback.async.AspectLogbackAsyncAppender;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;
import java.util.Map;
public class AsyncLuceneAppender extends AspectLogbackAsyncAppender {
@Override
protected void append(ILoggingEvent event) {
String traceId = AspectLogContext.getLogValue();
if (StringUtils.isEmpty(traceId)){
traceId = IdUtil.nanoId()+"@";
AspectLogContext.putLogValue(traceId);
}else {
if (!traceId.contains("@")){
AspectLogContext.putLogValue(traceId+"@");
}
}
if (StringUtils.isNotEmpty(traceId)){
MDC.put("traceId",traceId);
Map<String, String> mdcPropertyMap = event.getMDCPropertyMap();
if (mdcPropertyMap.getClass().getName().contains("SynchronizedMap")){
mdcPropertyMap.put("traceId",traceId);
}
MDC.clear();
}
super.append(event);
}
}

View File

@@ -0,0 +1,80 @@
package org.nl.modules.lucene.config;
/**
* @Author: lyd
* @Description: 定义lucene相关常量
* @Date: 2023/8/25
*/
public class LogMessageConstant {
/**
*
*/
public final static String SORT_NAME = "time";
/**
* 级别
*/
public final static String FIELD_LEVEL = "level";
/**
* 时间
*/
public final static String FIELD_TIMESTAMP = "timestamp";
/**
* 类的限定名
*/
public final static String FIELD_CLASS_NAME = "logger";
/**
* 线程名
*/
public final static String FIELD_THREAD = "thread";
/**
* 日志内容
*/
public final static String FIELD_MESSAGE = "message";
public final static String FIELD_TRACEID = "tlogTraceId";
// 定义颜色值
/**
* 文本颜色:黑色
*/
public final static String COLOR_BLACK = "\u001B[30m";
/**
* 文本颜色:红色
*/
public final static String COLOR_RED = "\u001B[31m";
/**
* 文本颜色:绿色
*/
public final static String COLOR_GREEN = "\u001B[32m";
/**
* 文本颜色:黄色
*/
public final static String COLOR_YELLOW = "\u001B[33m";
/**
* 文本颜色:蓝色
*/
public final static String COLOR_BLUE = "\u001B[34m";
/**
* 文本颜色:品红色
*/
public final static String COLOR_MAGENTA = "\u001B[35m";
/**
* 文本颜色:青色
*/
public final static String COLOR_CYAN = "\u001B[36m";
/**
* 文本颜色:白色
*/
public final static String COLOR_WHITE = "\u001B[37m";
/**
* 文本颜色重置
*/
public final static String COLOR_RESET = "\u001B[0m";
/**
* 背景颜色:黄色
*/
public final static String BACKGROUND_YELLOW = "\u001B[43m";
/**
* 索引路径
*/
public final static String INDEX_DIR = "E:\\lucene\\index";
}

View File

@@ -0,0 +1,133 @@
package org.nl.modules.lucene.config;
/**
* @author ldjun
* @version 1.0
* @date 2023年08月24日 13:00
* @desc desc
*/
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.ttl.TransmittableThreadLocal;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.NumericDocValuesField;
import org.apache.lucene.document.StringField;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.nl.modules.lucene.service.dto.LuceneLogDto;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.wltea.analyzer.lucene.IKAnalyzer;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.Properties;
public class LuceneAppender extends AppenderBase<ILoggingEvent> {
public static final TransmittableThreadLocal<String> traceIdTL = new TransmittableThreadLocal();
public LuceneProperties properties;
public static Directory index;
private List<LucenePropertyAndEncoder> encoders;
public static IndexWriter indexWriter;
@Override
public void start() {
super.start();
try {
init();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void init() throws IOException {
Resource resource = new ClassPathResource("config/application.yml");
YamlPropertiesFactoryBean yamlPropertiesFactoryBean = new YamlPropertiesFactoryBean();
yamlPropertiesFactoryBean.setResources(resource);
Properties properties = yamlPropertiesFactoryBean.getObject();
// 获取配置值
String luceneDir = properties.getProperty("lucene.index.path");
System.out.println("---index地址----" + luceneDir);
index = FSDirectory.open(Paths.get(luceneDir));
// 初始化 Lucene 索引
Analyzer analyzer = new IKAnalyzer();
IndexWriterConfig config = new IndexWriterConfig(analyzer);
indexWriter = new IndexWriter(index, config);
}
@Override
protected void append(ILoggingEvent event) {
String message = event.getFormattedMessage();
String[] split = message.split("@");
LuceneLogDto luceneLogDto = JSONObject.parseObject(split[1], LuceneLogDto.class);
Document document = new Document();
try {
//向document对象中添加域。
Map<String, String> mdcPropertyMap = event.getMDCPropertyMap();
String traceId = mdcPropertyMap.get("traceId");
System.out.println("---追踪号---"+traceId);
if (ObjectUtil.isNotEmpty(traceId)) {
document.add(new StringField("trace_id", traceId, Field.Store.YES));
}
if (ObjectUtil.isNotEmpty(luceneLogDto.getDevice_code())) {
document.add(new StringField("device_code", luceneLogDto.getDevice_code(), Field.Store.YES));
}
if (ObjectUtil.isNotEmpty(luceneLogDto.getContent())) {
document.add(new StringField("fieldContent", luceneLogDto.getContent(), Field.Store.YES));
}
if (ObjectUtil.isNotEmpty(luceneLogDto.getMethod())) {
document.add(new StringField("method", luceneLogDto.getMethod(), Field.Store.YES));
}
if (ObjectUtil.isNotEmpty(luceneLogDto.getStatus_code())) {
document.add(new StringField("status_code", luceneLogDto.getStatus_code(), Field.Store.YES));
}
if (ObjectUtil.isNotEmpty(luceneLogDto.getRequestparam())) {
document.add(new StringField("requestparam", luceneLogDto.getRequestparam(), Field.Store.YES));
}
if (ObjectUtil.isNotEmpty(luceneLogDto.getResponseparam())) {
document.add(new StringField("responseparam", luceneLogDto.getResponseparam(), Field.Store.YES));
}
document.add(new StringField("logType", luceneLogDto.getLogType(), Field.Store.YES));
document.add(new StringField("logTime", DateUtil.format(new DateTime(), "yyyy-MM-dd HH:mm:ss.SSS"), Field.Store.YES));
document.add(new NumericDocValuesField("logTime",System.currentTimeMillis()));//排序
try {
indexWriter.addDocument(document);
indexWriter.commit();
} catch (IOException e) {
e.printStackTrace();
}
} catch (Exception e) {
return;
}
}
@Override
public void stop() {
super.stop();
try {
indexWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void setProperties(LuceneProperties properties) {
this.properties = properties;
}
}

View File

@@ -0,0 +1,23 @@
package org.nl.modules.lucene.config;
import java.util.ArrayList;
import java.util.List;
public class LuceneProperties {
private List<Property> properties;
public LuceneProperties() {
this.properties = new ArrayList<Property>();
}
public List<Property> getProperties() {
return properties;
}
public void addProperty(Property property) {
properties.add(property);
}
}

View File

@@ -0,0 +1,38 @@
package org.nl.modules.lucene.config;
import ch.qos.logback.classic.PatternLayout;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.Context;
import ch.qos.logback.core.pattern.PatternLayoutBase;
/*
* @author ZZQ
* @Date 2023/12/22 18:11
*/
public class LucenePropertyAndEncoder {
private Property property;
private PatternLayoutBase layout = new PatternLayout();
public LucenePropertyAndEncoder(Property property, Context context) {
this.property = property;
this.layout.setContext(context);
this.layout.setPattern(String.valueOf(property.getValue()));
this.layout.setPostCompileProcessor(null);
this.layout.start();
}
public String encode(ILoggingEvent event) {
return layout.doLayout(event);
}
public String getName() {
return property.getName();
}
public boolean allowEmpty() {
return property.isAllowEmpty();
}
}

View File

@@ -0,0 +1,44 @@
package org.nl.modules.lucene.config;
/*
* @author ZZQ
* @Date 2023/12/26 15:30
*/
public class Property {
private String name;
private String value;
private boolean allowEmpty;
public Property() {
}
public Property(String name, String value, boolean allowEmpty) {
this.name = name;
this.value = value;
this.allowEmpty = allowEmpty;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public boolean isAllowEmpty() {
return allowEmpty;
}
public void setAllowEmpty(boolean allowEmpty) {
this.allowEmpty = allowEmpty;
}
}

View File

@@ -1,21 +0,0 @@
package org.nl.modules.lucene.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @deprecated 设置静态参数初始化
*/
@Configuration
public class StaticConfig {
//日志索引目录
@Value("${lucene.index.path}")
private String luceneDir;
@Bean
public int initStatic() {
UrlConfig.setLuceneUrl(luceneDir);
return 0;
}
}

View File

@@ -1,13 +0,0 @@
package org.nl.modules.lucene.config;
public class UrlConfig {
public static String luceneUrl;
public static String getLuceneUrl() {
return luceneUrl;
}
public static void setLuceneUrl(String luceneUrl) {
UrlConfig.luceneUrl = luceneUrl;
}
}

View File

@@ -26,11 +26,6 @@ public class LuceneController {
private final LuceneService luceneService;
@GetMapping("/labels/values")
@ApiOperation("获取标签")
public ResponseEntity<Object> labelsValues() {
return new ResponseEntity<>(luceneService.getLabelsValues(), HttpStatus.OK);
}
@GetMapping("/getAll")

View File

@@ -3,8 +3,6 @@ package org.nl.modules.lucene.service;
import org.nl.modules.lucene.service.dto.LuceneLogDto;
import java.io.IOException;
public interface LuceneExecuteLogService {
/**
* 设备光电变化实时光电信号
@@ -27,7 +25,7 @@ public interface LuceneExecuteLogService {
*
* @param luceneLogDto 日志结果对象
*/
void interfaceExecuteLog(LuceneLogDto luceneLogDto) throws IOException;
void interfaceExecuteLog(LuceneLogDto luceneLogDto);
/**
* 设备执行日志,会保留历史记录

View File

@@ -1,17 +1,11 @@
package org.nl.modules.lucene.service;
import com.alibaba.fastjson.JSONArray;
import org.springframework.data.domain.Pageable;
import java.util.Map;
public interface LuceneService {
/**
* 获取labels和values树
* @return
*/
JSONArray getLabelsValues();
/**
* 获取数据分页

View File

@@ -83,14 +83,15 @@ public class LuceneLogDto {
+ home;
}
public LuceneLogDto(final String device_code, final String item, final String last_signal,
final String signal) {
public LuceneLogDto(final String device_code, final String task_code,
final String instruct_code, final String method,
final String remark){
super();
this.device_code = device_code;
this.content = "信号 ["
+ item + "] 发生变更 "
+ last_signal + " -> "
+ signal;
this.task_code = task_code;
this.instruct_code = instruct_code;
this.method = method;
this.content = remark;
}
public LuceneLogDto(final String device_code, final String remark) {
@@ -98,24 +99,19 @@ public class LuceneLogDto {
this.device_code = device_code;
this.content = "设备 ["
+ device_code
+ "] : "
+ "] - "
+ remark;
}
public LuceneLogDto(final String device_code, final String item, final int last_info,
final int info) {
public LuceneLogDto(final LuceneLogDto dto) {
super();
String info_china = "";
switch(info){
case 0: info_china = "未联机";
case 1: info_china = "已联机";
case 2: break;
default:;
}
this.device_code = device_code;
this.content = "信号 ["
+item + "] 发生变更 "
+ last_info + " -> "
+ info;
this.method = method;
this.content = "设备 ["
+ device_code
+ "] - "
+ remark;
}
}

View File

@@ -1,24 +1,15 @@
package org.nl.modules.lucene.service.impl;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.lucene.document.*;
import org.apache.lucene.index.IndexWriter;
import org.nl.modules.lucene.common.LuceneServiceAutoRun;
import org.nl.modules.lucene.enums.LogTypeEnum;
import org.nl.modules.lucene.service.LuceneExecuteLogService;
import org.nl.modules.lucene.service.dto.LuceneLogDto;
import org.slf4j.MDC;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @author jlm
* @description 服务实现
@@ -28,71 +19,22 @@ import java.util.concurrent.atomic.AtomicInteger;
@RequiredArgsConstructor
@Slf4j
public class LuceneExecuteLogServiceImpl implements LuceneExecuteLogService {
private static AtomicInteger count = new AtomicInteger(0);
@Override
public void deviceItemValue(String device_code, String key, String value) {
String now = DateUtil.now();
}
@SneakyThrows
@Override
public void deviceExecuteLog(LuceneLogDto luceneLogDto) {
if (luceneLogDto!=null){
log.info("log:{}", JSON.toJSONString(luceneLogDto));
}
// luceneLogDto.setLogType(LogTypeEnum.DEVICE_LOG.getDesc());
// addIndex(luceneLogDto);
luceneLogDto.setLogType(LogTypeEnum.DEVICE_LOG.getDesc());
log.info("{}", JSON.toJSONString(luceneLogDto));
}
@Override
public void interfaceExecuteLog(LuceneLogDto luceneLogDto) throws IOException {
if (luceneLogDto!=null){
log.info("log:{}", JSON.toJSONString(luceneLogDto));
}
// luceneLogDto.setLogType(LogTypeEnum.INTERFACE_LOG.getDesc());
// addIndex(luceneLogDto);
}
private void addIndex(LuceneLogDto luceneLogDto) throws IOException {
IndexWriter indexWriter = LuceneServiceAutoRun.getIndexWriter();
//创建一个Document对象
Document document = new Document();
try {
//记录索引开始时间
long startTime = System.currentTimeMillis();
//向document对象中添加域。
if (ObjectUtil.isNotEmpty(luceneLogDto.getDevice_code())) {
document.add(new StringField("device_code", luceneLogDto.getDevice_code(), Field.Store.YES));
// document.add(new TextField("device_code", luceneLogDto.getDevice_code(), Field.Store.YES));
}
if (ObjectUtil.isNotEmpty(luceneLogDto.getContent())) {
document.add(new StringField("fieldContent", luceneLogDto.getContent(), Field.Store.YES));
}
if (ObjectUtil.isNotEmpty(luceneLogDto.getMethod())) {
document.add(new StringField("method", luceneLogDto.getMethod(), Field.Store.YES));
}
if (ObjectUtil.isNotEmpty(luceneLogDto.getStatus_code())) {
document.add(new StringField("status_code", luceneLogDto.getStatus_code(), Field.Store.YES));
}
if (ObjectUtil.isNotEmpty(luceneLogDto.getRequestparam())) {
document.add(new StringField("requestparam", luceneLogDto.getRequestparam(), Field.Store.YES));
}
if (ObjectUtil.isNotEmpty(luceneLogDto.getResponseparam())) {
document.add(new StringField("responseparam", luceneLogDto.getResponseparam(), Field.Store.YES));
}
document.add(new StringField("logType", luceneLogDto.getLogType(), Field.Store.YES));
document.add(new StringField("logTime", DateUtil.format(new DateTime(), "yyyy-MM-dd HH:mm:ss.SSS"), Field.Store.YES));
document.add(new NumericDocValuesField("logTime",System.currentTimeMillis()));//排序
indexWriter.addDocument(document);
//记录索引结束时间
long endTime = System.currentTimeMillis();
log.info("建立索引共耗时{}毫秒", endTime - startTime);
indexWriter.commit();
// MDC.put("DEVICECODE", luceneLogDto.getDevice_code());
} catch (Exception e) {
log.error(e.getMessage(), e);
}
public void interfaceExecuteLog(LuceneLogDto luceneLogDto) {
luceneLogDto.setLogType(LogTypeEnum.INTERFACE_LOG.getDesc());
log.info("{}", JSON.toJSONString(luceneLogDto));
}
@Override

View File

@@ -1,18 +1,24 @@
package org.nl.modules.lucene.service.impl;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.nl.modules.lucene.common.Searcher;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.*;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.BytesRef;
import org.nl.modules.lucene.service.LuceneService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import java.util.Map;
import java.nio.file.Paths;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
@Service
@@ -20,66 +26,102 @@ import java.util.Map;
@Slf4j
public class LuceneServiceImpl implements LuceneService {
@Value("${loki.url}")
private String lokiUrl;
@Value("${loki.systemName}")
private String systemName;
//日志索引目录
@Value("${lucene.index.path}")
private String luceneUrl;
/**
* 获取labels和values树
*
* @return
*/
@Override
public JSONArray getLabelsValues() {
JSONArray result = new JSONArray();
// 获取所有标签
String labelString = HttpUtil.get(lokiUrl + "/labels", CharsetUtil.CHARSET_UTF_8);
JSONObject parse = (JSONObject) JSONObject.parse(labelString);
JSONArray labels = parse.getJSONArray("data");
for (int i=0; i<labels.size(); i++) {
// 获取标签下的所有值
String valueString = HttpUtil.get(lokiUrl + "/label/" + labels.getString(i) + "/values", CharsetUtil.CHARSET_UTF_8);
JSONObject parse2 = (JSONObject) JSONObject.parse(valueString);
JSONArray values = parse2.getJSONArray("data");
JSONArray children = new JSONArray();
// 组成树形状态 两级
for (int j=0; j<values.size(); j++) {
JSONObject leaf = new JSONObject();
leaf.put("label", values.getString(j));
leaf.put("value", values.getString(j));
children.add(leaf);
}
JSONObject node = new JSONObject();
node.put("label", labels.getString(i));
node.put("value", labels.getString(i));
node.put("children", children);
result.add(node);
}
return result;
}
@Override
public Map<String, Object> getAll(Map whereJson, Pageable page) {
JSONObject jo = new JSONObject();
//获取要查询的路径,也就是索引所在的位置
try {
JSONObject jsonObject = (JSONObject) Searcher.search(luceneUrl, "", whereJson);
JSONArray array = jsonObject.getJSONArray("content");
int totalElements = Integer.parseInt(jsonObject.get("totalElements").toString());
jo.put("content", array);
jo.put("totalElements", totalElements);
FSDirectory directory = FSDirectory.open(Paths.get("C:\\acs\\lucene\\index"));
DirectoryReader open = DirectoryReader.open(directory);
IndexSearcher searcher = new IndexSearcher(open);
// 实际上Lucene本身不支持分页。因此我们需要自己进行逻辑分页。我们要准备分页参数
int pageSize = Integer.parseInt(whereJson.get("size").toString());// 每页条数
int pageNum = Integer.parseInt(whereJson.get("page").toString());// 当前页码
BooleanQuery.Builder booleanQueryBuilder = new BooleanQuery.Builder();
//时间范围查询
String startDate = (String) whereJson.get("begin_time");
String endDate = (String) whereJson.get("end_time");
if (startDate == null){
Calendar calendar=Calendar.getInstance();
calendar.set(1970, 0, 1);
startDate = DateUtil.format(calendar.getTime(),"yyyy-MM-dd HH:mm:ss.SSS");
}else{
startDate = getDate(startDate);
}
if (endDate == null){
endDate = DateUtil.format(new DateTime(),"yyyy-MM-dd HH:mm:ss.SSS");
} else {
endDate = getDate(endDate);
}
TermRangeQuery termRangeQuery = new TermRangeQuery("logTime", new BytesRef(startDate), new BytesRef(endDate), true, true);
booleanQueryBuilder.add(termRangeQuery,BooleanClause.Occur.MUST);
if (whereJson.get("device_code") != null){
Query termQuery = new TermQuery(new Term("device_code", (String) whereJson.get("device_code")));
booleanQueryBuilder.add(termQuery,BooleanClause.Occur.MUST);
}
if (whereJson.get("method") != null){
Query termQuery = new TermQuery(new Term("method", (String) whereJson.get("method")));
booleanQueryBuilder.add(termQuery,BooleanClause.Occur.MUST);
}
if (whereJson.get("status_code") != null){
Query termQuery = new TermQuery(new Term("status_code", (String) whereJson.get("status_code")));
booleanQueryBuilder.add(termQuery,BooleanClause.Occur.MUST);
}
if (whereJson.get("requestparam") != null){
WildcardQuery query = new WildcardQuery(new Term("requestparam", "*"+(String) whereJson.get("requestparam")+"*"));
booleanQueryBuilder.add(query,BooleanClause.Occur.MUST);
}
if (whereJson.get("responseparam") != null){
WildcardQuery query = new WildcardQuery(new Term("responseparam", "*"+(String) whereJson.get("responseparam")+"*"));
booleanQueryBuilder.add(query,BooleanClause.Occur.MUST);
}
if (whereJson.get("blurry") != null) {
WildcardQuery query = new WildcardQuery(new Term("fieldContent", "*"+(String) whereJson.get("blurry")+"*"));
booleanQueryBuilder.add(query, BooleanClause.Occur.MUST);
}
TopFieldCollector collector = TopFieldCollector.create(new Sort(new SortField("logTime", SortField.Type.LONG,true)), 20000, 0);
searcher.search(booleanQueryBuilder.build(), collector);
TopDocs topDocs = collector.topDocs(pageNum*pageSize, pageSize);
int totalSize = collector.getTotalHits();
ScoreDoc[] scoreDocs = topDocs.scoreDocs;
List<JSONObject> list = new ArrayList<>();
for (ScoreDoc scoreDoc : scoreDocs) {
Document doc = open.document(scoreDoc.doc);
JSONObject object = new JSONObject();
object.put("content",doc.get("fieldContent"));
object.put("device_code",doc.get("device_code"));
object.put("logTime",doc.get("logTime"));
object.put("method",doc.get("method"));
object.put("status_code",doc.get("status_code"));
object.put("requestparam",doc.get("requestparam"));
object.put("responseparam",doc.get("responseparam"));
if(doc.get("fieldContent") != null) {
list.add(object);
}
}
open.close();
directory.close();
JSONObject jo = new JSONObject();
jo.put("content", list);
jo.put("totalElements", totalSize);
return jo;
} catch (Exception e) {
log.error("索引查询为空", e);
throw new NullPointerException("索引查询为空");
}
}
return jo;
public static String getDate(String timeString) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX");//时间格式
Date date = sdf.parse(timeString);
timeString = DateUtil.format(date, "yyyy-MM-dd HH:mm:ss.SSS");//格式化后的时间
return timeString;
}
}