17 changed files with 1196 additions and 254 deletions
@ -0,0 +1,91 @@ |
|||||
|
package org.nl.acs.opc; |
||||
|
|
||||
|
import java.util.Date; |
||||
|
import java.util.HashMap; |
||||
|
import java.util.Map; |
||||
|
|
||||
|
public abstract class BlockedRunable implements Runnable { |
||||
|
private String threadName; |
||||
|
private Date startTime; |
||||
|
private Map<String, BlockedRunable> index = new HashMap(); |
||||
|
|
||||
|
public BlockedRunable() { |
||||
|
} |
||||
|
|
||||
|
public BlockedRunable(Map<String, BlockedRunable> index) { |
||||
|
this.index = index; |
||||
|
} |
||||
|
|
||||
|
public abstract String getCode(); |
||||
|
|
||||
|
public abstract void subRun() throws Exception; |
||||
|
|
||||
|
public void run() { |
||||
|
try { |
||||
|
this.setStartTime(new Date()); |
||||
|
this.setThreadName(Thread.currentThread().getName()); |
||||
|
this.subRun(); |
||||
|
} catch (Exception e) { |
||||
|
e.printStackTrace(); |
||||
|
} finally { |
||||
|
if (this.index.keySet().contains(this.getCode())) { |
||||
|
this.index.remove(this.getCode()); |
||||
|
} |
||||
|
|
||||
|
} |
||||
|
|
||||
|
} |
||||
|
|
||||
|
public String getThreadName() { |
||||
|
return this.threadName; |
||||
|
} |
||||
|
|
||||
|
public void setThreadName(String threadName) { |
||||
|
this.threadName = threadName; |
||||
|
} |
||||
|
|
||||
|
public Date getStartTime() { |
||||
|
return this.startTime; |
||||
|
} |
||||
|
|
||||
|
public void setStartTime(Date startTime) { |
||||
|
this.startTime = startTime; |
||||
|
} |
||||
|
|
||||
|
public Map<String, BlockedRunable> getIndex() { |
||||
|
return this.index; |
||||
|
} |
||||
|
|
||||
|
public void setIndex(Map<String, BlockedRunable> index) { |
||||
|
this.index = index; |
||||
|
} |
||||
|
|
||||
|
public int hashCode() { |
||||
|
int prime = 1; |
||||
|
int result = 1; |
||||
|
result = 31 * result + (this.getCode() == null ? 0 : this.getCode().hashCode()); |
||||
|
return result; |
||||
|
} |
||||
|
|
||||
|
public boolean equals(Object obj) { |
||||
|
if (this == obj) { |
||||
|
return true; |
||||
|
} else if (obj == null) { |
||||
|
return false; |
||||
|
} else if (this.getClass() != obj.getClass()) { |
||||
|
return false; |
||||
|
} else { |
||||
|
BlockedRunable other = (BlockedRunable) obj; |
||||
|
if (this.getCode() == null) { |
||||
|
if (other.getCode() != null) { |
||||
|
return false; |
||||
|
} |
||||
|
} else if (!this.getCode().equals(other.getCode())) { |
||||
|
return false; |
||||
|
} |
||||
|
|
||||
|
return true; |
||||
|
} |
||||
|
} |
||||
|
} |
||||
|
|
@ -0,0 +1,119 @@ |
|||||
|
package org.nl.acs.opc; |
||||
|
|
||||
|
import lombok.extern.slf4j.Slf4j; |
||||
|
import org.nl.acs.auto.run.AbstractAutoRunnable; |
||||
|
import org.nl.acs.device_driver.driver.ExecutableDeviceDriver; |
||||
|
import org.nl.config.thread.TheadFactoryName; |
||||
|
import org.springframework.beans.factory.annotation.Autowired; |
||||
|
import org.springframework.stereotype.Component; |
||||
|
|
||||
|
import java.util.*; |
||||
|
import java.util.concurrent.*; |
||||
|
|
||||
|
@Component |
||||
|
@Slf4j |
||||
|
public class DeviceExecuteAutoRun extends AbstractAutoRunnable { |
||||
|
@Autowired |
||||
|
DeviceAppService deviceAppService; |
||||
|
int cache_thread = 3; |
||||
|
|
||||
|
int corePoolSize = 50; |
||||
|
int maximumPoolSize = 100; |
||||
|
int queueLength = maximumPoolSize * cache_thread; |
||||
|
|
||||
|
int multiple = cache_thread; |
||||
|
|
||||
|
int loop_time_millions = 100; |
||||
|
ExecutorService executorService; |
||||
|
Map<String, BlockedRunable> runs; |
||||
|
|
||||
|
public DeviceExecuteAutoRun() { |
||||
|
// this.executorService = Executors.newCachedThreadPool();
|
||||
|
/* this.executorService=new ThreadPoolExecutor( |
||||
|
corePoolSize, |
||||
|
maximumPoolSize, |
||||
|
1L, |
||||
|
TimeUnit.SECONDS, |
||||
|
new ArrayBlockingQueue<>( queueLength), |
||||
|
new TheadFactoryName() |
||||
|
);*/ |
||||
|
this.executorService = new ThreadPoolExecutor( |
||||
|
10, |
||||
|
20, |
||||
|
1L, |
||||
|
TimeUnit.SECONDS, |
||||
|
new ArrayBlockingQueue<>(queueLength), |
||||
|
new TheadFactoryName(), new RejectedExecutionHandler() { |
||||
|
|
||||
|
@Override |
||||
|
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) { |
||||
|
if (!executor.isShutdown()) { |
||||
|
try { |
||||
|
executor.getQueue().put(r); |
||||
|
} catch (InterruptedException arg3) { |
||||
|
log.debug("", arg3); |
||||
|
} |
||||
|
} |
||||
|
} |
||||
|
} |
||||
|
); |
||||
|
this.runs = new LinkedHashMap(); |
||||
|
this.runs = Collections.synchronizedMap(this.runs); |
||||
|
} |
||||
|
|
||||
|
@Override |
||||
|
public String getCode() { |
||||
|
return DeviceExecuteAutoRun.class.getSimpleName(); |
||||
|
} |
||||
|
|
||||
|
|
||||
|
@Override |
||||
|
public String getName() { |
||||
|
return "设备执行线程"; |
||||
|
} |
||||
|
|
||||
|
@Override |
||||
|
public void autoRun() throws Exception { |
||||
|
for (int i = 0; !OpcStartTag.is_run; ++i) { |
||||
|
log.info("设备执行线程等待opc同步线程..."); |
||||
|
Thread.sleep(1000L); |
||||
|
if (i > 60) { |
||||
|
log.info("设备执行线程放弃等待opc同步线程..."); |
||||
|
break; |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
// Thread.sleep(10000L);
|
||||
|
log.info("设备执行线程开始..."); |
||||
|
|
||||
|
while (true) { |
||||
|
Thread.sleep((long) this.loop_time_millions); |
||||
|
List<ExecutableDeviceDriver> deviceDrivers = this.deviceAppService.findDeviceDriver(ExecutableDeviceDriver.class); |
||||
|
|
||||
|
Iterator it = deviceDrivers.iterator(); |
||||
|
while (it.hasNext()) { |
||||
|
final ExecutableDeviceDriver deviceDriver = (ExecutableDeviceDriver) it.next(); |
||||
|
//不包含正在执行的线程,则进行执行
|
||||
|
if (!this.runs.keySet().contains(deviceDriver.getDeviceCode())) { |
||||
|
BlockedRunable runnable = new BlockedRunable() { |
||||
|
@Override |
||||
|
public void subRun() throws Exception { |
||||
|
deviceDriver.executeAuto(); |
||||
|
} |
||||
|
|
||||
|
@Override |
||||
|
public String getCode() { |
||||
|
return deviceDriver.getDeviceCode(); |
||||
|
} |
||||
|
}; |
||||
|
if (!this.runs.keySet().contains(deviceDriver.getDeviceCode())) { |
||||
|
this.runs.put(deviceDriver.getDeviceCode(), runnable); |
||||
|
} |
||||
|
|
||||
|
runnable.setIndex(this.runs); |
||||
|
this.executorService.submit(runnable); |
||||
|
} |
||||
|
} |
||||
|
} |
||||
|
} |
||||
|
} |
@ -0,0 +1,432 @@ |
|||||
|
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.alicp.jetcache.anno.method.SpringCacheContext; |
||||
|
import lombok.extern.slf4j.Slf4j; |
||||
|
import org.nl.acs.opc.service.dto.OpcServerManageDto; |
||||
|
import org.nl.acs.udw.UnifiedDataAccessor; |
||||
|
import org.nl.acs.udw.UnifiedDataAccessorFactory; |
||||
|
import org.nl.acs.udw.UnifiedDataAppService; |
||||
|
import org.nl.config.SpringContextHolder; |
||||
|
import org.openscada.opc.lib.da.*; |
||||
|
import org.springframework.beans.factory.annotation.Autowired; |
||||
|
import org.springframework.stereotype.Service; |
||||
|
|
||||
|
import java.util.*; |
||||
|
|
||||
|
|
||||
|
@Slf4j |
||||
|
@Service |
||||
|
public class DeviceOpcProtocolRunable implements Runnable, DataCallback, ServerConnectionStateListener { |
||||
|
List<OpcItemDto> protocols; |
||||
|
OpcServerManageDto OpcServer; |
||||
|
int error_num; |
||||
|
String message; |
||||
|
int maxResartNum; |
||||
|
private Server server; |
||||
|
private Group group; |
||||
|
boolean flag = false; |
||||
|
private int all_null; |
||||
|
private Map<String, OpcItemDto> itemSearchCache; |
||||
|
|
||||
|
// @Autowired
|
||||
|
// OpcServerService opcServerService;
|
||||
|
|
||||
|
|
||||
|
public DeviceOpcProtocolRunable() { |
||||
|
this.error_num = 0; |
||||
|
this.all_null = 0; |
||||
|
this.message = null; |
||||
|
this.itemSearchCache = new HashMap(); |
||||
|
this.server = null; |
||||
|
} |
||||
|
|
||||
|
public List<OpcItemDto> getProtocols() { |
||||
|
return this.protocols; |
||||
|
} |
||||
|
|
||||
|
public void setProtocols(List<OpcItemDto> protocols) { |
||||
|
this.protocols = protocols; |
||||
|
} |
||||
|
|
||||
|
public OpcServerManageDto getOpcServer() { |
||||
|
return this.OpcServer; |
||||
|
} |
||||
|
|
||||
|
public void setOpcServer(OpcServerManageDto opcServer) { |
||||
|
this.OpcServer = opcServer; |
||||
|
} |
||||
|
|
||||
|
|
||||
|
private OpcItemDto getItem(String item) { |
||||
|
OpcItemDto x = (OpcItemDto) this.itemSearchCache.get(item); |
||||
|
if (x == null) { |
||||
|
Iterator var3 = this.protocols.iterator(); |
||||
|
|
||||
|
while (var3.hasNext()) { |
||||
|
OpcItemDto dto = (OpcItemDto) var3.next(); |
||||
|
if (StrUtil.equals(item, dto.getItem_code())) { |
||||
|
x = dto; |
||||
|
this.itemSearchCache.put(item, dto); |
||||
|
break; |
||||
|
} |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
return x; |
||||
|
} |
||||
|
|
||||
|
|
||||
|
@Override |
||||
|
public void run() { |
||||
|
if (OpcConfig.opc_item_read_using_callback) { |
||||
|
this.runNew(); |
||||
|
} else { |
||||
|
this.runOld(); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
|
||||
|
private void runOld() { |
||||
|
while (true) { |
||||
|
start: |
||||
|
try { |
||||
|
if (this.group != null) { |
||||
|
group.clear(); |
||||
|
group.remove(); |
||||
|
log.trace("清理group..."); |
||||
|
} |
||||
|
if (this.server != null) { |
||||
|
server.disconnect(); |
||||
|
log.trace("清理server..."); |
||||
|
} |
||||
|
OpcServerService opcServerService = SpringContextHolder.getBean(OpcServerService.class); |
||||
|
group =opcServerService.getServer(this.getOpcServer().getOpc_code()); |
||||
|
// this.server = OpcServerUtl.getServerWithOutException(this.OpcServer.getOpc_host(), this.OpcServer.getCls_id(), this.OpcServer.getUser(), this.OpcServer.getPassword(), this.OpcServer.getDomain());
|
||||
|
// this.server.addStateListener(this);
|
||||
|
// group = this.server.addGroup();
|
||||
|
List<String> itemsString = new ArrayList(); |
||||
|
Iterator var3 = this.protocols.iterator(); |
||||
|
|
||||
|
while (var3.hasNext()) { |
||||
|
OpcItemDto protocol = (OpcItemDto) var3.next(); |
||||
|
String item = protocol.getItem_code(); |
||||
|
itemsString.add(item); |
||||
|
} |
||||
|
|
||||
|
Map<String, Item> itemsMap = new LinkedHashMap(); |
||||
|
boolean is_error = false; |
||||
|
StringBuilder err_message = new StringBuilder(); |
||||
|
Iterator var6 = itemsString.iterator(); |
||||
|
|
||||
|
while (var6.hasNext()) { |
||||
|
String string = (String) var6.next(); |
||||
|
|
||||
|
try { |
||||
|
Item item = group.addItem(string); |
||||
|
itemsMap.put(string, item); |
||||
|
log.trace("添加成功 {}", string); |
||||
|
} catch (Exception var26) { |
||||
|
err_message.append(string + ":" + var26.getMessage()); |
||||
|
if (!is_error) { |
||||
|
is_error = true; |
||||
|
} |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
String tag; |
||||
|
if (is_error) { |
||||
|
tag = err_message.toString(); |
||||
|
log.warn("{}:{}", OpcConfig.resource_code, tag); |
||||
|
} |
||||
|
|
||||
|
if (!OpcStartTag.is_run) { |
||||
|
OpcStartTag.is_run = true; |
||||
|
} |
||||
|
|
||||
|
tag = ""; |
||||
|
if (log.isWarnEnabled()) { |
||||
|
tag = Thread.currentThread().getName(); |
||||
|
if (this.OpcServer != null) { |
||||
|
tag = tag + this.getOpcGroupID(); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
UnifiedDataAccessor accessor_value = UnifiedDataAccessorFactory.getAccessor(OpcConfig.udw_opc_value_key); |
||||
|
boolean time_out = false; |
||||
|
|
||||
|
while (DeviceOpcSynchronizeAutoRun.isRun) { |
||||
|
long begin = System.currentTimeMillis(); |
||||
|
if (log.isTraceEnabled()) { |
||||
|
log.trace("{} 开始记时{}", tag, DateUtil.now()); |
||||
|
} |
||||
|
|
||||
|
Map<Item, ItemState> itemStatus = group.read(true, (Item[]) itemsMap.values().toArray(new Item[0])); |
||||
|
long end = System.currentTimeMillis(); |
||||
|
long duration = end - begin; |
||||
|
if (log.isTraceEnabled()) { |
||||
|
log.trace("{} 读取耗时:{}", tag, duration); |
||||
|
} |
||||
|
|
||||
|
if (duration > 1000L) { |
||||
|
if (!time_out) { |
||||
|
log.warn("{} 读取超时 : {}", tag, duration); |
||||
|
} |
||||
|
|
||||
|
time_out = true; |
||||
|
} else { |
||||
|
time_out = false; |
||||
|
} |
||||
|
|
||||
|
boolean valueAllNotNull = false; |
||||
|
Set<Item> items = itemStatus.keySet(); |
||||
|
Iterator var18 = items.iterator(); |
||||
|
|
||||
|
while (var18.hasNext()) { |
||||
|
Item item = (Item) var18.next(); |
||||
|
ItemState itemState = (ItemState) itemStatus.get(item); |
||||
|
Object value = OpcUtl.getValue(item, itemState); |
||||
|
if (value != null) { |
||||
|
valueAllNotNull = true; |
||||
|
} |
||||
|
|
||||
|
String itemId = item.getId(); |
||||
|
Object his = accessor_value.getValue(itemId); |
||||
|
if (!ObjectUtl.isEquals(itemState.getQuality(), QualityTypeValue.OPC_QUALITY_GOOD) && his != null) { |
||||
|
log.warn("opc 值不健康 item: {}, 状态: {}", itemId, itemState.getQuality()); |
||||
|
valueAllNotNull = true; |
||||
|
} |
||||
|
|
||||
|
if (!UnifiedDataAppService.isEquals(value, his)) { |
||||
|
OpcItemDto itemDto = this.getItem(itemId); |
||||
|
if (true) { |
||||
|
this.logItemChanged(itemId, accessor_value, value, itemDto); |
||||
|
} |
||||
|
if(!ObjectUtil.isEmpty(value)){ |
||||
|
accessor_value.setValue(itemId, value); |
||||
|
} |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
end = System.currentTimeMillis(); |
||||
|
if (log.isTraceEnabled()) { |
||||
|
log.trace("{}", itemsString); |
||||
|
log.trace("{} 计算完成耗时{}", tag, end - begin); |
||||
|
} |
||||
|
|
||||
|
ThreadUtl.sleep((long) OpcConfig.synchronized_millisecond); |
||||
|
if (this.error_num != 0) { |
||||
|
this.error_num = 0; |
||||
|
this.message = null; |
||||
|
} |
||||
|
|
||||
|
if (!valueAllNotNull) { |
||||
|
int random = (new Random()).nextInt(10) + 1; |
||||
|
random *= 1000; |
||||
|
if (this.all_null < 3) { |
||||
|
if (log.isWarnEnabled()) { |
||||
|
log.warn("{} 所有内容都为空, all_null:{} ,暂定{}s", tag, all_null,5000 + random); |
||||
|
} |
||||
|
|
||||
|
ThreadUtl.sleep((long) (5000 + random)); |
||||
|
} else if (this.all_null < 6) { |
||||
|
if (log.isWarnEnabled()) { |
||||
|
log.warn(tag + "重新创建server"); |
||||
|
log.warn("{} 所有内容都为空, all_null:{} ,暂定{}s", tag, all_null,30000 + random); |
||||
|
} |
||||
|
// ThreadUtl.sleep((long) (30000 + random));
|
||||
|
ThreadUtl.sleep((long) ((new Random()).nextInt(3) +1) * 1000); |
||||
|
break start; |
||||
|
} else if (this.all_null < 12) { |
||||
|
if (log.isWarnEnabled()) { |
||||
|
log.warn("{} 所有内容都为空, all_null:{} ,暂定{}ms", tag, all_null, '\uea60' + random); |
||||
|
} |
||||
|
|
||||
|
ThreadUtl.sleep((long) ('\uea60' + random)); |
||||
|
} else { |
||||
|
if (log.isWarnEnabled()) { |
||||
|
log.warn("{} 所有内容都为空, all_null:{} ,暂定{}ms", tag, all_null, 120000 + random); |
||||
|
} |
||||
|
|
||||
|
ThreadUtl.sleep((long) (120000 + random)); |
||||
|
} |
||||
|
|
||||
|
++this.all_null; |
||||
|
} else { |
||||
|
this.all_null = 0; |
||||
|
} |
||||
|
// break start;
|
||||
|
|
||||
|
} |
||||
|
|
||||
|
log.warn("opc线程停止。。。"); |
||||
|
return; |
||||
|
} catch (Exception var27) { |
||||
|
if (this.server != null) { |
||||
|
try { |
||||
|
this.server.disconnect(); |
||||
|
} catch (Exception var25) { |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
this.server = null; |
||||
|
if (!DeviceOpcSynchronizeAutoRun.isRun) { |
||||
|
log.warn("opc线程停止2。。。"); |
||||
|
return; |
||||
|
} |
||||
|
|
||||
|
String error_message = "设备信息同步异常"; |
||||
|
if (!StrUtil.equals(this.message, error_message)) { |
||||
|
log.warn(error_message, var27); |
||||
|
} |
||||
|
|
||||
|
ThreadUtl.sleep((long) (OpcConfig.synchronized_exception_wait_second * 1000)); |
||||
|
++this.error_num; |
||||
|
if (this.error_num > 3 && !StrUtil.equals(this.message, error_message)) { |
||||
|
this.message = error_message; |
||||
|
} |
||||
|
} |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
|
||||
|
private void runNew() { |
||||
|
Async20Access accessor = null; |
||||
|
|
||||
|
while (true) { |
||||
|
String opcGroupId = this.getOpcGroupID(); |
||||
|
|
||||
|
try { |
||||
|
if (this.server == null) { |
||||
|
this.server = OpcServerUtl.getServerWithOutException(this.OpcServer.getOpc_host(), this.OpcServer.getCls_id(), this.OpcServer.getUser(), this.OpcServer.getPassword(), this.OpcServer.getDomain()); |
||||
|
this.server.addStateListener(this); |
||||
|
accessor = new Async20Access(this.server, OpcConfig.synchronized_millisecond, true); |
||||
|
Iterator var9 = this.protocols.iterator(); |
||||
|
|
||||
|
while (var9.hasNext()) { |
||||
|
OpcItemDto protocol = (OpcItemDto) var9.next(); |
||||
|
String itemId = protocol.getItem_code(); |
||||
|
accessor.addItem(itemId, this); |
||||
|
} |
||||
|
|
||||
|
accessor.bind(); |
||||
|
log.info("Async20Access bind {}", opcGroupId); |
||||
|
} |
||||
|
|
||||
|
Thread.sleep((long) (OpcConfig.synchronized_exception_wait_second * 1000)); |
||||
|
} catch (Exception var8) { |
||||
|
if (accessor != null) { |
||||
|
try { |
||||
|
log.warn("Async20Access unbind {}", opcGroupId); |
||||
|
accessor.unbind(); |
||||
|
} catch (Exception var7) { |
||||
|
var7.printStackTrace(); |
||||
|
} |
||||
|
|
||||
|
accessor = null; |
||||
|
} |
||||
|
|
||||
|
if (this.server != null) { |
||||
|
try { |
||||
|
this.server.disconnect(); |
||||
|
} catch (Exception var6) { |
||||
|
} |
||||
|
|
||||
|
this.server = null; |
||||
|
} |
||||
|
|
||||
|
if (var8 instanceof InterruptedException) { |
||||
|
log.warn("OPC 同步线程(%s)被中断", opcGroupId); |
||||
|
return; |
||||
|
} |
||||
|
|
||||
|
log.warn("设备信息同步异常", var8); |
||||
|
ThreadUtl.sleep((long) (OpcConfig.synchronized_exception_wait_second * 1000)); |
||||
|
String error_message = var8.getMessage(); |
||||
|
if (error_message == null) { |
||||
|
error_message = var8.toString(); |
||||
|
} |
||||
|
|
||||
|
++this.error_num; |
||||
|
if (this.error_num > 3 && !StrUtil.equals(this.message, error_message)) { |
||||
|
this.message = error_message; |
||||
|
} |
||||
|
} |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
|
||||
|
public void connectionStateChanged(boolean connected) { |
||||
|
if (!connected) { |
||||
|
this.server = null; |
||||
|
} |
||||
|
|
||||
|
log.warn("opc server {} {}", this.getOpcGroupID(), connected ? "connected" : "disconnected"); |
||||
|
} |
||||
|
|
||||
|
private String getOpcGroupID() { |
||||
|
String var10000 = this.OpcServer.getOpc_code(); |
||||
|
return var10000 + "(" + this.protocols.size() + " items)"; |
||||
|
} |
||||
|
|
||||
|
public static String formatDuring(long mss) { |
||||
|
long days = mss / 86400000L; |
||||
|
long hours = mss % 86400000L / 3600000L; |
||||
|
long minutes = mss % 3600000L / 60000L; |
||||
|
long seconds = mss % 60000L / 1000L; |
||||
|
return days + " days " + hours + " hours " + minutes + " minutes " + seconds + " seconds "; |
||||
|
} |
||||
|
|
||||
|
|
||||
|
public void changed(Item item, ItemState itemState) { |
||||
|
String itemId = item.getId(); |
||||
|
|
||||
|
try { |
||||
|
Object value = OpcUtl.getValue(item, itemState); |
||||
|
UnifiedDataAccessor accessor_value = UnifiedDataAccessorFactory.getAccessor(OpcConfig.udw_opc_value_key); |
||||
|
accessor_value.setValue(itemId, value); |
||||
|
|
||||
|
// if (value != null) {
|
||||
|
// if (log.isTraceEnabled()) {
|
||||
|
// log.trace("Item {} new value: {}, Timestamp: {}", new Object[]{itemId, itemState.getValue(), itemState.getTimestamp().getTime()});
|
||||
|
// }
|
||||
|
// } else if (log.isInfoEnabled()) {
|
||||
|
// log.info("Item {} new value: {}, Timestamp: {}, Quality: {}", new Object[]{itemId, itemState.getValue(), itemState.getTimestamp().getTime(), itemState.getQuality()});
|
||||
|
// }
|
||||
|
log.trace("Item {} new value: {}, Timestamp: {}", new Object[]{itemId, itemState.getValue(), itemState.getTimestamp().getTime()}); |
||||
|
|
||||
|
OpcItemDto itemDto = this.getItem(itemId); |
||||
|
// if (Boolean.TRUE.equals(itemDto.getNeed_log())) {
|
||||
|
// this.logItemChanged(itemId, accessor_value, value, itemDto);
|
||||
|
// }
|
||||
|
this.logItemChanged(itemId, accessor_value, value, itemDto); |
||||
|
|
||||
|
} catch (Exception var7) { |
||||
|
log.error(itemId, var7); |
||||
|
} |
||||
|
|
||||
|
} |
||||
|
|
||||
|
private void logItemChanged(String itemId, UnifiedDataAccessor accessor_value, Object value, OpcItemDto itemDto) { |
||||
|
Object his = accessor_value.getValue(itemId); |
||||
|
List<String> relate_items = itemDto.getRelate_items(); |
||||
|
if (relate_items != null && !relate_items.isEmpty()) { |
||||
|
StringBuilder sb = new StringBuilder(); |
||||
|
Iterator var8 = relate_items.iterator(); |
||||
|
|
||||
|
while (var8.hasNext()) { |
||||
|
String relate = (String) var8.next(); |
||||
|
Object obj = accessor_value.getValue(relate); |
||||
|
sb.append("key:" + relate + "value:" + obj + ";"); |
||||
|
} |
||||
|
log.warn("设备:{}信号{}变更从{}->{};信号快照:{}", new Object[]{itemDto.getDevice_code(), itemId, his, value, sb}); |
||||
|
// this.businessLogger.setResource(itemDto.getDevice_code(), itemDto.getDevice_name()).log("信号{}变更从{}->{};信号快照:{}", new Object[]{itemId, his, value, sb});
|
||||
|
} else { |
||||
|
log.warn("设备:{}信号{}变更从{}->{};信号快照:{}", new Object[]{itemDto.getDevice_code(), itemId, his, value}); |
||||
|
// this.businessLogger.setResource(itemDto.getDevice_code(), itemDto.getDevice_name()).log("信号{}变更从{}->{}", new Object[]{itemId, his, value});
|
||||
|
} |
||||
|
} |
||||
|
|
||||
|
} |
@ -0,0 +1,83 @@ |
|||||
|
package org.nl.acs.opc; |
||||
|
|
||||
|
import cn.hutool.core.util.ObjectUtil; |
||||
|
import org.nl.acs.auto.run.AbstractAutoRunnable; |
||||
|
import org.nl.acs.opc.service.dto.OpcServerManageDto; |
||||
|
import org.springframework.beans.factory.annotation.Autowired; |
||||
|
import org.springframework.stereotype.Component; |
||||
|
|
||||
|
import java.util.Iterator; |
||||
|
import java.util.List; |
||||
|
import java.util.Map; |
||||
|
import java.util.Set; |
||||
|
import java.util.concurrent.ExecutorService; |
||||
|
import java.util.concurrent.Executors; |
||||
|
|
||||
|
/** |
||||
|
* OPC设备同步启动 |
||||
|
*/ |
||||
|
@Component |
||||
|
public class DeviceOpcSynchronizeAutoRun extends AbstractAutoRunnable { |
||||
|
|
||||
|
public static boolean isRun = false; |
||||
|
ExecutorService executorService = Executors.newCachedThreadPool(); |
||||
|
@Autowired |
||||
|
private DeviceAppService deviceAppService; |
||||
|
@Autowired |
||||
|
private OpcServerManageService opcServerManageService; |
||||
|
|
||||
|
@Override |
||||
|
public String getCode() { |
||||
|
return DeviceOpcSynchronizeAutoRun.class.getSimpleName(); |
||||
|
} |
||||
|
|
||||
|
@Override |
||||
|
public String getName() { |
||||
|
return "opc设备同步器"; |
||||
|
} |
||||
|
|
||||
|
@Override |
||||
|
public void autoRun() throws Exception { |
||||
|
{ |
||||
|
isRun = true; |
||||
|
|
||||
|
Map<String, OpcServerManageDto> servers = this.opcServerManageService.queryAllServerMap(); |
||||
|
Map<String, List<List<OpcItemDto>>> pros; |
||||
|
do{ |
||||
|
Thread.sleep(1000L); |
||||
|
pros = this.deviceAppService.findAllFormatProtocolFromDriver(); |
||||
|
}while (ObjectUtil.isEmpty(pros)); |
||||
|
Set<String> keys = pros.keySet(); |
||||
|
Iterator var4 = keys.iterator(); |
||||
|
//代码执行一次
|
||||
|
while (var4.hasNext()) { |
||||
|
String key = (String) var4.next(); |
||||
|
List<List<OpcItemDto>> list = (List) pros.get(key); |
||||
|
OpcServerManageDto opcServer = (OpcServerManageDto) servers.get(key); |
||||
|
Iterator var8 = list.iterator(); |
||||
|
while (var8.hasNext()) { |
||||
|
List<OpcItemDto> groupProtols = (List) var8.next(); |
||||
|
DeviceOpcProtocolRunable runable = new DeviceOpcProtocolRunable(); |
||||
|
runable.setProtocols(groupProtols); |
||||
|
runable.setOpcServer(opcServer); |
||||
|
this.executorService.submit(runable); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
// 同步无光电设备信号
|
||||
|
//Map<String, List<List<OpcItemDto>>> pros1 = this.deviceAppService.findAllFormatProtocolFromDriver();
|
||||
|
//List<DeviceDriver> opcDrivers = this.deviceAppService.findDeviceDriver(DeviceDriver.class);
|
||||
|
|
||||
|
while (true) { |
||||
|
Thread.sleep(3000L); |
||||
|
} |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
@Override |
||||
|
public void after() { |
||||
|
isRun = false; |
||||
|
this.executorService.shutdownNow(); |
||||
|
this.executorService = Executors.newCachedThreadPool(); |
||||
|
} |
||||
|
} |
@ -0,0 +1,70 @@ |
|||||
|
package org.nl.acs.opc; |
||||
|
|
||||
|
|
||||
|
import java.util.Arrays; |
||||
|
import java.util.Objects; |
||||
|
|
||||
|
public class ObjectUtl { |
||||
|
private ObjectUtl() { |
||||
|
} |
||||
|
|
||||
|
public static boolean isEquals(Object a, Object b) { |
||||
|
if (a == null && b == null) { |
||||
|
return true; |
||||
|
} else if (a != null && b != null) { |
||||
|
if (a.getClass().isArray()) { |
||||
|
if (a instanceof boolean[]) { |
||||
|
return Arrays.equals((boolean[]) ((boolean[]) a), (boolean[]) ((boolean[]) b)); |
||||
|
} else if (a instanceof byte[]) { |
||||
|
return Arrays.equals((byte[]) ((byte[]) a), (byte[]) ((byte[]) b)); |
||||
|
} else if (a instanceof int[]) { |
||||
|
return Arrays.equals((int[]) ((int[]) a), (int[]) ((int[]) b)); |
||||
|
} else if (a instanceof long[]) { |
||||
|
return Arrays.equals((long[]) ((long[]) a), (long[]) ((long[]) b)); |
||||
|
} else if (a instanceof double[]) { |
||||
|
return Arrays.equals((double[]) ((double[]) a), (double[]) ((double[]) b)); |
||||
|
} else if (a instanceof short[]) { |
||||
|
return Arrays.equals((short[]) ((short[]) a), (short[]) ((short[]) b)); |
||||
|
} else if (a instanceof char[]) { |
||||
|
return Arrays.equals((char[]) ((char[]) a), (char[]) ((char[]) b)); |
||||
|
} else if (a instanceof float[]) { |
||||
|
return Arrays.equals((float[]) ((float[]) a), (float[]) ((float[]) b)); |
||||
|
} else if (a instanceof Object[]) { |
||||
|
return Arrays.equals((Object[]) ((Object[]) a), (Object[]) ((Object[]) b)); |
||||
|
} else { |
||||
|
throw new RuntimeException("未实现"); |
||||
|
} |
||||
|
} else { |
||||
|
return Objects.equals(a, b); |
||||
|
} |
||||
|
} else { |
||||
|
return false; |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
public static boolean isTrue(Boolean boolean_) { |
||||
|
return boolean_ != null && isEquals(boolean_, true); |
||||
|
} |
||||
|
|
||||
|
public static boolean isTrue(Boolean targetBoolean, boolean defaultBoolean) { |
||||
|
return targetBoolean == null ? defaultBoolean : targetBoolean; |
||||
|
} |
||||
|
|
||||
|
public static boolean isFalse(Boolean boolean_) { |
||||
|
return boolean_ != null && isEquals(boolean_, false); |
||||
|
} |
||||
|
|
||||
|
|
||||
|
|
||||
|
|
||||
|
|
||||
|
public static boolean isObject(Class<?> clazz) { |
||||
|
if (clazz == null) { |
||||
|
return false; |
||||
|
} else if (clazz.getClass().isArray()) { |
||||
|
return false; |
||||
|
} else { |
||||
|
return Object.class.isAssignableFrom(clazz); |
||||
|
} |
||||
|
} |
||||
|
} |
@ -0,0 +1,5 @@ |
|||||
|
package org.nl.acs.opc; |
||||
|
|
||||
|
public class OpcStartTag { |
||||
|
public static boolean is_run = false; |
||||
|
} |
@ -0,0 +1,52 @@ |
|||||
|
/* |
||||
|
* Copyright 2019-2020 Zheng Jie |
||||
|
* |
||||
|
* Licensed under the Apache License, Version 2.0 (the "License"); |
||||
|
* you may not use this file except in compliance with the License. |
||||
|
* You may obtain a copy of the License at |
||||
|
* |
||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
* |
||||
|
* Unless required by applicable law or agreed to in writing, software |
||||
|
* distributed under the License is distributed on an "AS IS" BASIS, |
||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
||||
|
* See the License for the specific language governing permissions and |
||||
|
* limitations under the License. |
||||
|
*/ |
||||
|
package org.nl.config; |
||||
|
|
||||
|
import org.springframework.context.annotation.Bean; |
||||
|
import org.springframework.context.annotation.Configuration; |
||||
|
import org.springframework.web.cors.CorsConfiguration; |
||||
|
import org.springframework.web.cors.UrlBasedCorsConfigurationSource; |
||||
|
import org.springframework.web.filter.CorsFilter; |
||||
|
import org.springframework.web.servlet.config.annotation.EnableWebMvc; |
||||
|
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; |
||||
|
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; |
||||
|
|
||||
|
/** |
||||
|
* WebMvcConfigurer |
||||
|
* |
||||
|
* @author Zheng Jie |
||||
|
* @date 2018-11-30 |
||||
|
*/ |
||||
|
@Configuration |
||||
|
@EnableWebMvc |
||||
|
public class ConfigurerAdapter implements WebMvcConfigurer { |
||||
|
/** 文件配置 */ |
||||
|
private final FileProperties properties; |
||||
|
|
||||
|
public ConfigurerAdapter(FileProperties properties) { |
||||
|
this.properties = properties; |
||||
|
} |
||||
|
|
||||
|
@Override |
||||
|
public void addResourceHandlers(ResourceHandlerRegistry registry) { |
||||
|
FileProperties.ElPath path = properties.getPath(); |
||||
|
String avatarUtl = "file:" + path.getAvatar().replace("\\","/"); |
||||
|
String pathUtl = "file:" + path.getPath().replace("\\","/"); |
||||
|
registry.addResourceHandler("/avatar/**").addResourceLocations(avatarUtl).setCachePeriod(0); |
||||
|
registry.addResourceHandler("/file/**").addResourceLocations(pathUtl).setCachePeriod(0); |
||||
|
registry.addResourceHandler("/**").addResourceLocations("classpath:/META-INF/resources/").setCachePeriod(0); |
||||
|
} |
||||
|
} |
@ -1,184 +1,184 @@ |
|||||
package org.nl.config.lucene; |
package org.nl.config.lucene;//package org.nl.config.lucene;
|
||||
|
//
|
||||
import com.alibaba.fastjson.JSONObject; |
//import com.alibaba.fastjson.JSONObject;
|
||||
import org.apache.commons.io.FileUtils; |
//import org.apache.commons.io.FileUtils;
|
||||
import org.apache.lucene.analysis.Analyzer; |
//import org.apache.lucene.analysis.Analyzer;
|
||||
import org.apache.lucene.document.Document; |
//import org.apache.lucene.document.Document;
|
||||
import org.apache.lucene.document.Field; |
//import org.apache.lucene.document.Field;
|
||||
import org.apache.lucene.document.TextField; |
//import org.apache.lucene.document.TextField;
|
||||
import org.apache.lucene.index.IndexWriter; |
//import org.apache.lucene.index.IndexWriter;
|
||||
import org.apache.lucene.index.IndexWriterConfig; |
//import org.apache.lucene.index.IndexWriterConfig;
|
||||
import org.apache.lucene.store.Directory; |
//import org.apache.lucene.store.Directory;
|
||||
import org.apache.lucene.store.FSDirectory; |
//import org.apache.lucene.store.FSDirectory;
|
||||
import org.springframework.beans.factory.annotation.Value; |
//import org.springframework.beans.factory.annotation.Value;
|
||||
import org.wltea.analyzer.lucene.IKAnalyzer; |
//import org.wltea.analyzer.lucene.IKAnalyzer;
|
||||
|
//
|
||||
import java.io.BufferedReader; |
//import java.io.BufferedReader;
|
||||
import java.io.File; |
//import java.io.File;
|
||||
import java.io.FileReader; |
//import java.io.FileReader;
|
||||
import java.io.IOException; |
//import java.io.IOException;
|
||||
import java.nio.file.Paths; |
//import java.nio.file.Paths;
|
||||
import java.util.Set; |
//import java.util.Set;
|
||||
|
//
|
||||
/** |
///**
|
||||
* lucene索引器 |
// * lucene索引器
|
||||
*/ |
// */
|
||||
public class Indexer { |
//public class Indexer {
|
||||
/** |
// /**
|
||||
* 写索引实例 |
// * 写索引实例
|
||||
*/ |
// */
|
||||
private IndexWriter writer; |
// private IndexWriter writer;
|
||||
|
//
|
||||
public IndexWriter getWriter() { |
// public IndexWriter getWriter() {
|
||||
return writer; |
// return writer;
|
||||
} |
// }
|
||||
|
//
|
||||
/** |
// /**
|
||||
* 构造方法,实例化IndexWriter |
// * 构造方法,实例化IndexWriter
|
||||
* |
// *
|
||||
* @param indexDir |
// * @param indexDir
|
||||
* @throws Exception |
// * @throws Exception
|
||||
*/ |
// */
|
||||
public Indexer(String indexDir) throws Exception { |
// public Indexer(String indexDir) throws Exception {
|
||||
Directory dir = FSDirectory.open(Paths.get(indexDir)); |
// Directory dir = FSDirectory.open(Paths.get(indexDir));
|
||||
//标准分词器,会自动去掉空格啊,is a the等单词
|
// //标准分词器,会自动去掉空格啊,is a the等单词
|
||||
// Analyzer analyzer = new StandardAnalyzer();
|
//// Analyzer analyzer = new StandardAnalyzer();
|
||||
Analyzer analyzer = new IKAnalyzer(); |
// Analyzer analyzer = new IKAnalyzer();
|
||||
//将标准分词器配到写索引的配置中
|
// //将标准分词器配到写索引的配置中
|
||||
IndexWriterConfig config = new IndexWriterConfig(analyzer); |
// IndexWriterConfig config = new IndexWriterConfig(analyzer);
|
||||
//实例化写索引对象
|
// //实例化写索引对象
|
||||
writer = new IndexWriter(dir, config); |
// writer = new IndexWriter(dir, config);
|
||||
} |
// }
|
||||
|
//
|
||||
/** |
// /**
|
||||
* 索引指定目录下的所有文件 |
// * 索引指定目录下的所有文件
|
||||
* |
// *
|
||||
* @param dataDir |
// * @param dataDir
|
||||
* @return |
// * @return
|
||||
* @throws Exception |
// * @throws Exception
|
||||
*/ |
// */
|
||||
public int indexAll(String dataDir) throws Exception { |
// public int indexAll(String dataDir) throws Exception {
|
||||
// 获取该路径下的所有文件
|
// // 获取该路径下的所有文件
|
||||
File[] files = new File(dataDir).listFiles(); |
// File[] files = new File(dataDir).listFiles();
|
||||
if (null != files) { |
// if (null != files) {
|
||||
for (File file : files) { |
// for (File file : files) {
|
||||
//调用下面的indexFile方法,对每个文件进行索引
|
// //调用下面的indexFile方法,对每个文件进行索引
|
||||
indexFile(file); |
// indexFile(file);
|
||||
} |
// }
|
||||
} |
// }
|
||||
//返回索引的文件数
|
// //返回索引的文件数
|
||||
// return writer.numDocs();
|
//// return writer.numDocs();
|
||||
return writer.numRamDocs(); |
// return writer.numRamDocs();
|
||||
} |
// }
|
||||
|
//
|
||||
/** |
// /**
|
||||
* 索引指定的文件 |
// * 索引指定的文件
|
||||
* |
// *
|
||||
* @param file |
// * @param file
|
||||
* @throws Exception |
// * @throws Exception
|
||||
*/ |
// */
|
||||
private void indexFile(File file) throws Exception { |
// private void indexFile(File file) throws Exception {
|
||||
System.out.println("索引文件的路径:" + file.getCanonicalPath()); |
// System.out.println("索引文件的路径:" + file.getCanonicalPath());
|
||||
//调用下面的getDocument方法,获取该文件的document
|
// //调用下面的getDocument方法,获取该文件的document
|
||||
Document doc = getDocument(file); |
// Document doc = getDocument(file);
|
||||
//添加索引文档
|
// //添加索引文档
|
||||
//Document doc = json2Doc(jsonDoc);
|
// //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();
|
// 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.add(new TextField("contents", new FileReader(file)));
|
||||
//将doc添加到索引中
|
// //添加文件名,并把这个字段存到索引文件里
|
||||
writer.addDocument(doc); |
// doc.add(new TextField("fileName", file.getName(), Field.Store.YES));
|
||||
} |
// //添加文件路径
|
||||
|
// doc.add(new TextField("fullPath", file.getCanonicalPath(), Field.Store.YES));
|
||||
/** |
// return doc;
|
||||
* 获取文档,文档里再设置每个字段,就类似于数据库中的一行记录 |
// }
|
||||
* |
//
|
||||
* @param file |
// public Document json2Doc(String strDoc) {
|
||||
* @return |
// Document doc = new Document();
|
||||
* @throws Exception |
// JSONObject jsonDoc = JSONObject.parseObject(strDoc);
|
||||
*/ |
// Set<String> keys = jsonDoc.keySet();
|
||||
private Document getDocument(File file) throws Exception { |
// for (String key : keys) {
|
||||
Document doc = new Document(); |
// doc.add(new TextField(key, jsonDoc.getString(key), Field.Store.YES));
|
||||
//开始添加字段
|
// }
|
||||
//添加内容
|
// return doc;
|
||||
doc.add(new TextField("contents", new FileReader(file))); |
// }
|
||||
//添加文件名,并把这个字段存到索引文件里
|
//
|
||||
doc.add(new TextField("fileName", file.getName(), Field.Store.YES)); |
// public void addLogIndex(String msg) throws IOException {
|
||||
//添加文件路径
|
// //步骤一:创建Directory对象,用于指定索引库的位置 RAMDirectory内存
|
||||
doc.add(new TextField("fullPath", file.getCanonicalPath(), Field.Store.YES)); |
// Directory directory = FSDirectory.open(new File("D:\\lucene\\index").toPath());
|
||||
return doc; |
// //步骤二:创建一个IndexWriter对象,用于写索引
|
||||
} |
//// Analyzer analyzer = new StandardAnalyzer();
|
||||
|
// IndexWriter indexWriter = new IndexWriter(directory, new IndexWriterConfig(new IKAnalyzer(false)));
|
||||
public Document json2Doc(String strDoc) { |
//// indexWriter.deleteAll();//清理所有索引库
|
||||
Document doc = new Document(); |
//// IndexWriter indexWriter=new IndexWriter(directory,new IndexWriterConfig(new StandardAnalyzer()));
|
||||
JSONObject jsonDoc = JSONObject.parseObject(strDoc); |
// //记录索引开始时间
|
||||
Set<String> keys = jsonDoc.keySet(); |
// long startTime = System.currentTimeMillis();
|
||||
for (String key : keys) { |
// //步骤三:读取磁盘中文件,对应每一个文件创建一个文档对象
|
||||
doc.add(new TextField(key, jsonDoc.getString(key), Field.Store.YES)); |
// Document document = new Document();
|
||||
} |
//// document.add(new TextField("fieldContent", device_id, Field.Store.YES));
|
||||
return doc; |
// document.add(new TextField("fieldContent", msg, Field.Store.YES));
|
||||
} |
// indexWriter.addDocument(document);
|
||||
|
// //记录索引结束时间
|
||||
public void addLogIndex(String msg) throws IOException { |
// long endTime = System.currentTimeMillis();
|
||||
//步骤一:创建Directory对象,用于指定索引库的位置 RAMDirectory内存
|
// System.out.println("建立索引" + "共耗时" + (endTime - startTime) + "毫秒");
|
||||
Directory directory = FSDirectory.open(new File("D:\\lucene\\index").toPath()); |
// indexWriter.commit();
|
||||
//步骤二:创建一个IndexWriter对象,用于写索引
|
// //步骤八:关闭资源
|
||||
// Analyzer analyzer = new StandardAnalyzer();
|
// indexWriter.close();
|
||||
IndexWriter indexWriter = new IndexWriter(directory, new IndexWriterConfig(new IKAnalyzer(false))); |
// 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.deleteAll();//清理所有索引库
|
||||
// IndexWriter indexWriter=new IndexWriter(directory,new IndexWriterConfig(new StandardAnalyzer()));
|
//// indexWriter=new IndexWriter(directory,new IndexWriterConfig(new StandardAnalyzer()));
|
||||
//记录索引开始时间
|
// //记录索引开始时间
|
||||
long startTime = System.currentTimeMillis(); |
// long startTime = System.currentTimeMillis();
|
||||
//步骤三:读取磁盘中文件,对应每一个文件创建一个文档对象
|
// //步骤三:读取磁盘中文件,对应每一个文件创建一个文档对象
|
||||
Document document = new Document(); |
// File file = new File("D:\\testlog");
|
||||
// document.add(new TextField("fieldContent", device_id, Field.Store.YES));
|
// //步骤四:获取文件列表
|
||||
document.add(new TextField("fieldContent", msg, Field.Store.YES)); |
// File[] files = file.listFiles();
|
||||
indexWriter.addDocument(document); |
// for (File item : files) {
|
||||
//记录索引结束时间
|
// BufferedReader bufferedReader = new BufferedReader(new FileReader(item));
|
||||
long endTime = System.currentTimeMillis(); |
// String strLine = null;
|
||||
System.out.println("建立索引" + "共耗时" + (endTime - startTime) + "毫秒"); |
// while (null != (strLine = bufferedReader.readLine())) {
|
||||
indexWriter.commit(); |
// Document document = new Document();
|
||||
//步骤八:关闭资源
|
//// document.add(new Field());
|
||||
indexWriter.close(); |
// document.add(new TextField("fieldContent", strLine, Field.Store.YES));
|
||||
System.out.println("建立索引成功-----关闭资源"); |
// indexWriter.addDocument(document);
|
||||
} |
// }
|
||||
|
// }
|
||||
//系统的日志文件路径
|
// //记录索引结束时间
|
||||
@Value("${logging.file.path}") |
// long endTime = System.currentTimeMillis();
|
||||
private String logUrl; |
// System.out.println("建立索引" + "共耗时" + (endTime - startTime) + "毫秒");
|
||||
|
// indexWriter.commit();
|
||||
public static void main(String[] args) throws IOException { |
// //步骤八:关闭资源
|
||||
//步骤一:创建Directory对象,用于指定索引库的位置 RAMDirectory内存
|
// indexWriter.close();
|
||||
Directory directory = FSDirectory.open(new File("D:\\lucene\\index").toPath()); |
// System.out.println("建立索引成功-----关闭资源");
|
||||
//步骤二:创建一个IndexWriter对象,用于写索引
|
// }
|
||||
// Analyzer analyzer = new StandardAnalyzer();
|
//}
|
||||
IndexWriter indexWriter = new IndexWriter(directory, new IndexWriterConfig(new IKAnalyzer(false))); |
|
||||
|
|
||||
indexWriter.deleteAll();//清理所有索引库
|
|
||||
// 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("建立索引成功-----关闭资源"); |
|
||||
} |
|
||||
} |
|
||||
|
@ -1,60 +1,60 @@ |
|||||
package org.nl.config.lucene; |
package org.nl.config.lucene;//package org.nl.config.lucene;
|
||||
|
//
|
||||
import cn.hutool.core.date.DateUtil; |
//import cn.hutool.core.date.DateUtil;
|
||||
import org.apache.lucene.index.CorruptIndexException; |
//import org.apache.lucene.index.CorruptIndexException;
|
||||
import org.apache.lucene.index.IndexWriter; |
//import org.apache.lucene.index.IndexWriter;
|
||||
import org.apache.lucene.index.IndexWriterConfig; |
//import org.apache.lucene.index.IndexWriterConfig;
|
||||
import org.apache.lucene.store.Directory; |
//import org.apache.lucene.store.Directory;
|
||||
import org.apache.lucene.store.FSDirectory; |
//import org.apache.lucene.store.FSDirectory;
|
||||
import org.wltea.analyzer.lucene.IKAnalyzer; |
//import org.wltea.analyzer.lucene.IKAnalyzer;
|
||||
|
//
|
||||
import java.io.File; |
//import java.io.File;
|
||||
import java.io.IOException; |
//import java.io.IOException;
|
||||
import java.text.ParseException; |
//import java.text.ParseException;
|
||||
import java.text.SimpleDateFormat; |
//import java.text.SimpleDateFormat;
|
||||
import java.util.Date; |
//import java.util.Date;
|
||||
|
//
|
||||
public class LuceneIndexWriter { |
//public class LuceneIndexWriter {
|
||||
private static IndexWriter indexWriter; |
// private static IndexWriter indexWriter;
|
||||
|
//
|
||||
static { |
// static {
|
||||
try { |
// try {
|
||||
Directory directory = FSDirectory.open(new File(UrlConfig.luceneUrl).toPath()); |
// Directory directory = FSDirectory.open(new File(UrlConfig.luceneUrl).toPath());
|
||||
IndexWriterConfig config = new IndexWriterConfig(new IKAnalyzer()); |
// IndexWriterConfig config = new IndexWriterConfig(new IKAnalyzer());
|
||||
indexWriter = new IndexWriter(directory, config); |
// indexWriter = new IndexWriter(directory, config);
|
||||
} catch (Exception e) { |
// } catch (Exception e) {
|
||||
e.printStackTrace(); |
// e.printStackTrace();
|
||||
} |
// }
|
||||
/**当当前线程结束时,自动关闭IndexWriter,使用Runtime对象*/ |
// /**当当前线程结束时,自动关闭IndexWriter,使用Runtime对象*/
|
||||
Runtime.getRuntime().addShutdownHook(new Thread(() -> { |
// Runtime.getRuntime().addShutdownHook(new Thread(() -> {
|
||||
try { |
// try {
|
||||
closeIndexWriter(); |
// closeIndexWriter();
|
||||
} catch (Exception e) { |
// } catch (Exception e) {
|
||||
e.printStackTrace(); |
// e.printStackTrace();
|
||||
} |
// }
|
||||
})); |
// }));
|
||||
} |
// }
|
||||
/**在线程结束时,自动关闭IndexWriter*/ |
// /**在线程结束时,自动关闭IndexWriter*/
|
||||
public static IndexWriter getIndexWriter() { |
// public static IndexWriter getIndexWriter() {
|
||||
return indexWriter; |
// return indexWriter;
|
||||
} |
// }
|
||||
/**关闭IndexWriter |
// /**关闭IndexWriter
|
||||
* @throws IOException |
// * @throws IOException
|
||||
* @throws CorruptIndexException */ |
// * @throws CorruptIndexException */
|
||||
public static void closeIndexWriter() throws Exception { |
// public static void closeIndexWriter() throws Exception {
|
||||
if(indexWriter != null) { |
// if(indexWriter != null) {
|
||||
indexWriter.close(); |
// indexWriter.close();
|
||||
} |
// }
|
||||
} |
// }
|
||||
|
//
|
||||
public static void main(String[] args) throws IOException { |
// public static void main(String[] args) throws IOException {
|
||||
indexWriter.deleteAll(); |
// indexWriter.deleteAll();
|
||||
} |
// }
|
||||
|
//
|
||||
public static String getDate(String timeString) throws ParseException { |
// public static String getDate(String timeString) throws ParseException {
|
||||
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX");//时间格式
|
// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX");//时间格式
|
||||
Date date = sdf.parse(timeString); |
// Date date = sdf.parse(timeString);
|
||||
timeString = DateUtil.format(date, "yyyy-MM-dd HH:mm:ss.SSS");//格式化后的时间
|
// timeString = DateUtil.format(date, "yyyy-MM-dd HH:mm:ss.SSS");//格式化后的时间
|
||||
return timeString; |
// return timeString;
|
||||
} |
// }
|
||||
} |
//}
|
||||
|
@ -0,0 +1,86 @@ |
|||||
|
package org.nl.config.lucene; |
||||
|
|
||||
|
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.system.service.param.ISysParamService; |
||||
|
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 ISysParamService 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; |
||||
|
} |
||||
|
|
||||
|
} |
Loading…
Reference in new issue