write this code in an easier way: import org.apache.commons.lang3.StringUtils; import…
- User
write this code in an easier way:
import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.dao.DataAccessException; import org.springframework.data.redis.core.RedisOperations; import org.springframework.data.redis.core.SessionCallback; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.core.ValueOperations; import org.springframework.stereotype.Service;
import java.time.Instant; import java.time.LocalDateTime; import java.util.List; import java.util.concurrent.TimeUnit;
@Service public class RedisRateLimiter {
codeprivate static final Logger logger = LoggerFactory.getLogger(RedisRateLimiter.class); @Autowired private StringRedisTemplate stringTemplate; private static final int REQUESTS_PER_HOUR = 10; public boolean isAllowed(String username) { final int hour = LocalDateTime.now().getHour(); String key = username + ":" + hour; ValueOperations<String, String> operations = stringTemplate.opsForValue(); String requests = operations.get(key); if (StringUtils.isNotBlank(requests) && Integer.parseInt(requests) >= REQUESTS_PER_HOUR) { return false; } List<Object> txResults = stringTemplate.execute(new SessionCallback<>() { @Override public <K, V> List<Object> execute(RedisOperations<K, V> operations) throws DataAccessException { final StringRedisTemplate redisTemplate = (StringRedisTemplate) operations; final ValueOperations<String, String> valueOperations = redisTemplate.opsForValue(); operations.multi(); valueOperations.increment(key); redisTemplate.expire(key, 2, TimeUnit.HOURS); // This will contain the results of all operations in the transaction return operations.exec(); } }); logger.info("Current request count: " + txResults.get(0)); return true; } public void service() { for (int i=0; i<20; i++) { boolean allowed = isAllowed("carvia"); if(!allowed) break; } } - Assistant
import java.time.LocalDateTime; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.dao.DataAccessException; import org.springframework.data.redis.core.RedisOperations; import org.springframework.data.redis.core.SessionCallback; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.core.ValueOperations; import org.springframework.stereotype.Service; import java.util.List; import java.util.concurrent.TimeUnit;
- User
i have a more containers deployed on kubernetes, and i want to count and rate limit te api calls using redis, how could i integrate it with spring?
- Assistant