springboot如何判断Redis Stream消费组是否存在

public class StreamMqTest {
    @Autowired
    private RedisConnectionFactory redisConnectionFactory;
    @Autowired
    private StreamRedisQueue streamRedisQueue;
    @Autowired
    private RedisTemplate redisTemplate;
    @Test
    public void createGroup(){
        streamRedisQueue.createGroup("stream_key", "suiye");
        streamRedisQueue.createGroup("stream_key", "lasse");
    }

    @Test
    public void doIsStreamGroupExist() {
        boolean consumerGroupExists = isStreamGroupExists("stream_key", "lasse");
        System.out.println("完成任务");
    }

    public boolean isStreamGroupExists(String streamKey, String groupName) {
        RedisStreamCommands commands = redisConnectionFactory.getConnection().streamCommands();

        //首先检查Stream Key是否存在,否则下面代码可能会因为尝试检查不存在的Stream Key而导致异常
        if (!redisTemplate.hasKey(streamKey)){
            return false;
        }

        //获取streamKey下的所有groups
        StreamInfo.XInfoGroups xInfoGroups = commands.xInfoGroups(streamKey.getBytes());
        AtomicBoolean exists= new AtomicBoolean(false);
        xInfoGroups.forEach(xInfoGroup -> {
            if (xInfoGroup.groupName().equals(groupName)){
                exists.set(true);
            }
        });

        return exists.get();
    }

}

你可能感兴趣的:(常用,redis,spring,boot,java)