Spring Data Redis - 支持命令 PUBSUB CHANNELS

Spring Data Redis - Support for command PUBSUB CHANNELS

RedisTemplate 不支持 PUBSUB CHANNELS 命令。所以一种方法是执行以下操作

   private JedisPool getJedisPool(){
        if (jedisPool == null)
        jedisPool = new JedisPool(redisConnectionFactory.getPoolConfig(), redisConnectionFactory.getHostName(), redisConnectionFactory.getPort());
        return jedisPool;
    }

    public Integer getNumChannels() {
        Integer count = 0;
        try (Jedis jedis = getJedisPool().getResource()) {
            List<String> channels = jedis.pubsubChannels("user.*");
            count = channels == null ? 0 : channels.size();
        } catch (Exception e) {
            logger.error("unable to get user count", e);
        } finally {
            //getJedisPool().close(); //No need for close or returnResource()
        }
    }

这是建议的方法吗?

这取决于您要去哪里。 如果您打算只将它用于您自己的应用程序,那么您可以从 JedisConnectionFactory 获取一个 JedisConnection 并使用底层 Jedis 实例来调用命令。

JedisConnectionFactory factory = …

// assuming you're using Redis Standalone or Redis Sentinel
RedisConnection connection = factory.getConnection();
try {
    if (connection instanceof JedisConnection) {
        Jedis jedis = ((JedisConnection) connection).getNativeConnection();
        List<String> strings = jedis.pubsubChannels("…");
    }
} finally {
    connection.close();
}

请注意,这仅适用于 Redis Standalone/Redis Sentinel,但不适用于 Redis Cluster,因为 JedisCluster 不会公开 pubsubChannels