1

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()
        }
    }

这是建议的方法吗?

4

1 回答 1

0

这取决于你要去哪里。如果您打算仅将它用于您自己的应用程序,那么您可以获取JedisConnectionfromJedisConnectionFactory并使用底层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

于 2016-03-19T17:26:37.873 回答