protocolSession的缓存改为同步caffeine,因为没有IO操作

This commit is contained in:
三丙
2024-10-09 10:08:32 +08:00
parent a1db728be5
commit 4356eaba85
10 changed files with 74 additions and 58 deletions

View File

@@ -47,7 +47,7 @@ public abstract class ProtocolMessageProcessor {
}));
}
protected abstract void uplinkHandle(ListenerToHandlerMsg listenerToHandlerMsg) throws Exception;
protected abstract void uplinkHandle(ListenerToHandlerMsg listenerToHandlerMsg);
public void downlinkHandle(SessionToHandlerMsg sessionToHandlerMsg, MessagesStats downlinkMsgStats) throws DownlinkException {
try {
@@ -62,5 +62,5 @@ public abstract class ProtocolMessageProcessor {
}
}
protected abstract void downlinkHandle(SessionToHandlerMsg sessionToHandlerMsg) throws Exception;
protected abstract void downlinkHandle(SessionToHandlerMsg sessionToHandlerMsg);
}

View File

@@ -20,7 +20,6 @@ import sanbing.jcpp.protocol.domain.ProtocolSession;
import sanbing.jcpp.protocol.provider.ProtocolSessionRegistryProvider;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
/**
* @author baigod
@@ -44,14 +43,14 @@ public class DownlinkController {
final DeferredResult<ResponseEntity<String>> response = new DeferredResult<>(onDownlinkTimeout,
ResponseEntity.status(HttpStatus.REQUEST_TIMEOUT).build());
UUID protocolSessionId = new UUID(downlinkMsg.getSessionIdMSB(),downlinkMsg.getSessionIdLSB()) ;
UUID protocolSessionId = new UUID(downlinkMsg.getSessionIdMSB(), downlinkMsg.getSessionIdLSB());
CompletableFuture<ProtocolSession> protocolSessionCompletableFuture = protocolSessionRegistryProvider.get(protocolSessionId);
ProtocolSession protocolSession = protocolSessionRegistryProvider.get(protocolSessionId);
protocolSessionCompletableFuture.thenAccept(session -> {
if (session != null) {
try {
if (protocolSession != null) {
session.onDownlink(downlinkMsg);
protocolSession.onDownlink(downlinkMsg);
response.setResult(ResponseEntity.status(HttpStatus.OK).build());
} else {
@@ -60,17 +59,15 @@ public class DownlinkController {
response.setResult(ResponseEntity.status(HttpStatus.NOT_FOUND).body("Protocol Session not found for ID:" + protocolSessionId));
}
}).whenComplete((unused, throwable) -> {
if (throwable != null) {
} catch (Exception e) {
log.warn("下发报文时处理失败 sessionId: {}", protocolSessionId, throwable);
log.warn("下发报文时处理失败 sessionId: {}", protocolSessionId, e);
if (!response.isSetOrExpired()) {
if (!response.isSetOrExpired()) {
response.setResult(ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(throwable.getMessage()));
}
response.setResult(ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage()));
}
});
}
return response;
}

View File

@@ -7,7 +7,6 @@ package sanbing.jcpp.protocol.provider;
import sanbing.jcpp.protocol.domain.ProtocolSession;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
/**
* @author baigod
@@ -21,7 +20,7 @@ public interface ProtocolSessionRegistryProvider {
void unregister(UUID sessionId);
CompletableFuture<ProtocolSession> get(UUID sessionId);
ProtocolSession get(UUID sessionId);
/**
* 活跃会话

View File

@@ -4,7 +4,7 @@
*/
package sanbing.jcpp.protocol.provider.impl;
import com.github.benmanes.caffeine.cache.AsyncCache;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
@@ -20,7 +20,6 @@ import sanbing.jcpp.protocol.provider.ProtocolSessionRegistryProvider;
import java.time.LocalDateTime;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
@@ -33,6 +32,7 @@ import java.util.concurrent.TimeUnit;
@Slf4j
public class DefaultProtocolSessionRegistryProvider implements ProtocolSessionRegistryProvider {
private static final int INIT_CACHE_LIMIT = 100_000;
private static final int MAXIMUM_SIZE = 1_000_000;
@Value("${service.protocols.sessions.default-inactivity-timeout-in-sec}")
private int defaultInactivityTimeoutInSec;
@@ -41,23 +41,18 @@ public class DefaultProtocolSessionRegistryProvider implements ProtocolSessionRe
private int defaultStateCheckIntervalInSec;
@Getter
private final AsyncCache<UUID, ProtocolSession> SESSION_CACHE = buildCache();
private final Cache<UUID, ProtocolSession> sessionCache = buildCache();
private final ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(JCPPThreadFactory.forName("session-state-checker"));
@PostConstruct
public void init() {
scheduledExecutorService.scheduleAtFixedRate(() ->
SESSION_CACHE.asMap().forEach((id, sessionCompletableFuture) ->
sessionCompletableFuture.whenComplete((protocolSession, throwable) -> {
if (throwable == null && protocolSession != null) {
if (protocolSession.getLastActivityTime().isBefore(LocalDateTime.now().minusSeconds(defaultInactivityTimeoutInSec))) {
protocolSession.close(SessionCloseReason.INACTIVE);
unregister(protocolSession.getId());
}
}
})
), defaultStateCheckIntervalInSec, defaultStateCheckIntervalInSec, TimeUnit.SECONDS);
scheduledExecutorService.scheduleAtFixedRate(() -> sessionCache.asMap().forEach((id, session) -> {
if (session.getLastActivityTime().isBefore(LocalDateTime.now().minusSeconds(defaultInactivityTimeoutInSec))) {
session.close(SessionCloseReason.INACTIVE);
unregister(session.getId());
}
}), defaultStateCheckIntervalInSec, defaultStateCheckIntervalInSec, TimeUnit.SECONDS);
}
@PreDestroy
@@ -72,7 +67,7 @@ public class DefaultProtocolSessionRegistryProvider implements ProtocolSessionRe
log.debug("Registering session {}", protocolSession);
}
SESSION_CACHE.put(protocolSession.getId(), CompletableFuture.supplyAsync(() -> protocolSession, ThreadPoolConfiguration.JCPP_COMMON_THREAD_POOL));
sessionCache.put(protocolSession.getId(), protocolSession);
}
@@ -81,16 +76,15 @@ public class DefaultProtocolSessionRegistryProvider implements ProtocolSessionRe
log.info("Unregistering session {}", sessionId);
SESSION_CACHE.synchronous().invalidate(sessionId);
sessionCache.invalidate(sessionId);
}
@Override
public CompletableFuture<ProtocolSession> get(UUID sessionId) {
public ProtocolSession get(UUID sessionId) {
log.debug("Get session {}", sessionId);
return SESSION_CACHE.get(sessionId, uuid -> null);
return sessionCache.get(sessionId, uuid -> null);
}
@Override
@@ -102,14 +96,14 @@ public class DefaultProtocolSessionRegistryProvider implements ProtocolSessionRe
protocolSession.setLastActivityTime(LocalDateTime.now());
SESSION_CACHE.put(protocolSession.getId(), CompletableFuture.supplyAsync(() -> protocolSession, ThreadPoolConfiguration.JCPP_COMMON_THREAD_POOL));
sessionCache.put(protocolSession.getId(), protocolSession);
}
private AsyncCache<UUID, ProtocolSession> buildCache() {
private Cache<UUID, ProtocolSession> buildCache() {
return Caffeine.newBuilder()
.initialCapacity(INIT_CACHE_LIMIT)
.maximumSize(INIT_CACHE_LIMIT * 10)
.maximumSize(MAXIMUM_SIZE)
.executor(ThreadPoolConfiguration.JCPP_COMMON_THREAD_POOL)
.buildAsync();
.build();
}
}