Асинхронный поток не может получить обновленную информацию о репозитории.JAVA

Программисты JAVA общаются здесь
Ответить
Anonymous
 Асинхронный поток не может получить обновленную информацию о репозитории.

Сообщение Anonymous »

Application.properties

Код: Выделить всё

custom.async.executor.corePoolSize=3
custom.async.executor.maxPoolSize=5
custom.async.executor.queueCapacity=2
custom.async.executor.threadNamePrefix=serverAsyncThread-

custom.driver.socket=http://localhost:4444
custom.driver.timeoutSecs=3

custom.websocket.port=8080
custom.websocket.sendIntervalMilli=1000

custom.session.persistSecs=3
custom.session.checkIntervalMilli=2000

server.port=8080
spring.application.name=archive-ingestion-server
spring.threads.virtual.enabled=true
spring.lifecycle.timeout-per-shutdown-phase=3s
Конфигурация веб-сокета

Код: Выделить всё

@Configuration
@EnableWebSocketMessageBroker
public class ServerWebsocketConfig implements WebSocketMessageBrokerConfigurer {
@Value("${custom.websocket.port:8080}")
private Integer port;

public void registerStompEndpoints(StompEndpointRegistry websocketRegistry) {
websocketRegistry.addEndpoint("/api/v1/websocket")
.setAllowedOriginPatterns("http://localhost:" + this.port + "*");
}

public void configureMessageBroker(MessageBrokerRegistry brokerRegistry) {
brokerRegistry.enableSimpleBroker("/api/v1/websocket/topic");
brokerRegistry.setApplicationDestinationPrefixes("/api/v1/websocket/app");
}
}
Асинхронная конфигурация

Код: Выделить всё

@Bean(name = "serverAsyncExecutor")
public Executor getAsyncExecutor()  {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(this.corePoolSize);
// Two additional thread for the session monitoring loop and driver creation
executor.setMaxPoolSize(this.maxPoolSize+2);
executor.setQueueCapacity(this.queueCapacity);
executor.setThreadNamePrefix(this.threadNamePrefix);
executor.initialize();
return executor;
}

@Bean
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return new ServerAsyncExceptionHandler();
}
Моя проблема заключается в том, что асинхронный поток, который я вызываю для публикации постоянных обновлений текущего сеанса, не работает должным образом. Я вызываю функцию getSessionInformationLive() через вызов API REST к моему контроллеру, и он, в свою очередь, отправляет обратно подтверждающее сообщение и запускает асинхронный цикл, в котором, пока цикл не получит ответ с установленным флагом завершения, через регулярные промежутки времени публикуются обновления моего сеанса.

Код: Выделить всё

@Async("serverAsyncExecutor")
public void runLiveSessionFeed(String sessionId) throws InterruptedException {
ServerResponseData responseData;
boolean sessionStillLive;
do {
// Get session entity information
Thread.sleep(this.sendIntervalMilli);
responseData = this.getSessionInformation(sessionId);

// Send response data
this.websocketTemplate.convertAndSend("/api/v1/websocket/topic/get-session-live", responseData);

// Log it
this.logService.createInfoLog(this.messageService.createWSSentMessage(sessionId, responseData.getResponseMessage()));

// Run a check to decide if to continue
boolean messageIsFail = responseData.getResponseMessage().equals(
this.messageService.getResponseGetSessionFailed()
);
boolean sessionComplete = responseData.isSessionFinished() || responseData.isSessionCanceled() ||
responseData.isSessionException();

sessionStillLive = !messageIsFail && !sessionComplete;
} while (sessionStillLive);
}

public ServerResponseData getSessionInformationLive(String sessionId) throws InterruptedException {
// Validate the session ID
boolean sessionIdValid = this.validateSessionId(sessionId);
if (!sessionIdValid) {
return new ServerResponseData(sessionId, this.messageService.getResponseBadSessionId());
}

// Start sending through websockets
this.runLiveSessionFeed(sessionId);

// Return the response
return new ServerResponseData(sessionId, this.messageService.getResponseNewSessionFeed());
}
Для дальнейшего контекста «this.getSessionInformation(sessionId)» вызывает функцию, которая обращается к базе данных H2 для получения последней информации о сеансе. Это используется в этом активном варианте функции и как ответ на собственную конечную точку API. Я протестировал функцию getSessionInformation, чтобы убедиться, что она по-прежнему работает и отлично работает при вызове с использованием запроса HTTP GET, как показано ниже:

Код: Выделить всё

2025-12-18T23:09:44.295-05:00  INFO 14472 --- [archive-ingestion-server] [erAsyncThread-2] c.l.i.ao3.services.ArchiveLogService     : Session service retrieved session 702f10fc1acd57577f728fd1a50537142ceda512b0acb108040689369970f11b.

2025-12-18T23:09:44.296-05:00  INFO 14472 --- [archive-ingestion-server] [erAsyncThread-2] c.l.i.ao3.services.ArchiveLogService     : Session service updated last recorded message for session 702f10fc1acd57577f728fd1a50537142ceda512b0acb108040689369970f11b to: Added text -> Not sure what she got this time, you go to where she was beside your home computer. She had managed to hook herself up by USB, resting against the table as she did everything through the USB. You look at the mouse and keyboard still on the counter, seeing the pointer icon zooming around on the screen by itself.

2025-12-18T23:09:44.334-05:00  INFO 14472 --- [archive-ingestion-server] [           main] c.l.i.ao3.services.ArchiveLogService     : Session service retrieved session 702f10fc1acd57577f728fd1a50537142ceda512b0acb108040689369970f11b.

Response message -> Added text -> Not sure what she got this time, you go to where she was beside your home computer. She had managed to hook herself up by USB, resting against the table as she did everything through the USB. You look at the mouse and keyboard still on the counter, seeing the pointer icon zooming around on the screen by itself.

On update 9 for session ID 702f10fc1acd57577f728fd1a50537142ceda512b0acb108040689369970f11b...
Что мне следует изменить, чтобы я мог сделать то же самое и для моего цикла веб-сокетов?

Подробнее здесь: https://stackoverflow.com/questions/798 ... nformation
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «JAVA»