连接缓存 Connection Cache
引入maven依赖
<dependency>
<groupId>org.apache.plc4x</groupId>
<artifactId>plc4j-connection-cache</artifactId>
<version>0.12.0</version>
</dependency>
配置
PlcConnectionManager connectionManager = CachedPlcConnectionManager.getBuilder()
.withMaxLeaseTime(Duration.ofSeconds(10))
.withMaxWaitTime(Duration.ofMinutes(1))
.build();
例子:
public static void main(String[] args) throws Exception {
PlcConnectionManager connectionManager = CachedPlcConnectionManager.getBuilder().build();
for (int i = 0; i < 10000; i++) {
try(PlcConnection connection = connectionManager.getConnection("s7://192.168.1.192")) {
if (connection.isConnected()){
PlcReadRequest.Builder builder = connection.readRequestBuilder();
builder.addTagAddress("PollingValue", "%DB1:4.0:BOOL");
PlcReadRequest readRequest = builder.build();
PlcReadResponse syncResponse = readRequest.execute().get(2000, TimeUnit.MILLISECONDS);
printResponse(syncResponse);
} else {
logger.info("PLC is not connected, let's try again to connect");
connection.connect();
}
} catch (PlcConnectionException e){
logger.error("Connection exception in trying to connect", e);
} catch (CancellationException e){
logger.error("Polling Thread canceled", e);
} catch (IllegalStateException e){
logger.error("Error in Netty state machine", e);
} catch (ExecutionException e){
logger.error("Interrupted Exception fired", e);
} catch (TimeoutException e) {
logger.error("Timeout exception fired", e);
}
TimeUnit.MILLISECONDS.sleep(100);
}
System.exit(0);
}