All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.infusers.core.sse.requests.RequestTrackingService Maven / Gradle / Ivy

There is a newer version: 2024.12.0008
Show newest version
package com.infusers.core.sse.requests;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import com.infusers.core.logger.ILogger;

@Service
public class RequestTrackingService {

    private static final String ACTIVE_REQUEST_COUNT_KEY = "active_request_count";

    private ILogger log = new ILogger(RequestTrackingService.class);
    private static final String CLASS_NAME = "RequestTrackingService";

    @Autowired
    private StringRedisTemplate redisTemplate;
    
    @Autowired
    private ApplicationEventPublisher eventPublisher;    

    public void incrementRequestCount() {
        redisTemplate.opsForValue().increment(ACTIVE_REQUEST_COUNT_KEY);
        publishActiveRequestCount();
    }

    public void decrementRequestCount() {
        Long currentCount = redisTemplate.opsForValue().decrement(ACTIVE_REQUEST_COUNT_KEY);
        if (currentCount != null && currentCount < 0) {
            log.error(CLASS_NAME + ".decrementRequestCount()--> Warning: Request count dropped below zero. Resetting to zero.");
            redisTemplate.opsForValue().set(ACTIVE_REQUEST_COUNT_KEY, "0");
        }
        publishActiveRequestCount();
    }

    public long getActiveRequestCount() {
        String count = redisTemplate.opsForValue().get(ACTIVE_REQUEST_COUNT_KEY);
        return count != null ? Long.parseLong(count) : 0;
    }

    private void publishActiveRequestCount() {
        long count = getActiveRequestCount();
        log.debug(CLASS_NAME + ".publishActiveRequestCount()--> count = " + count);
        
        eventPublisher.publishEvent(new ActiveRequestCountEvent(this, count));        
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy