package ru.mtusi.messenger; import jakarta.annotation.PostConstruct; import org.springframework.data.redis.connection.stream.Consumer; import org.springframework.data.redis.connection.stream.MapRecord; import org.springframework.data.redis.connection.stream.ReadOffset; import org.springframework.data.redis.connection.stream.RecordId; import org.springframework.data.redis.connection.stream.StreamRecords; import org.springframework.data.redis.connection.stream.StreamOffset; import org.springframework.data.redis.connection.stream.StreamReadOptions; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Component; import java.time.Duration; import java.util.List; import java.util.Map; @Component public class JobBroker { public static final String STREAM = "messenger:attachment-jobs"; public static final String GROUP = "attachment-workers"; private final StringRedisTemplate redis; public JobBroker(StringRedisTemplate redis) { this.redis = redis; } @PostConstruct void ensureGroup() { try { redis.opsForStream().createGroup(STREAM, ReadOffset.from("0-0"), GROUP); } catch (RuntimeException ignored) { /* BUSYGROUP means it already exists. */ } } public void publish(String jobId) { MapRecord record = StreamRecords.newRecord() .in(STREAM).ofMap(Map.of("job_id", jobId, "schema_version", "1", "type", "attachment.process.v1")); redis.opsForStream().add(record); } public MapRecord read(String consumer) { List> records = redis.opsForStream().read( Consumer.from(GROUP, consumer), StreamReadOptions.empty().count(1).block(Duration.ofSeconds(1)), StreamOffset.create(STREAM, ReadOffset.lastConsumed())); return records == null || records.isEmpty() ? null : records.getFirst(); } public void ack(RecordId id) { redis.opsForStream().acknowledge(STREAM, GROUP, id); } }