2016-03-18 77 views
1

RedisTemplate不支持PUBSUB CHANNELS命令。因此,一種方法將做到以下幾點:Spring Data Redis - 支持命令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() 
     } 
    } 

這是建議的方法嗎?

回答

0

這取決於你前往的目的地。 如果您打算僅將它用於您自己的應用程序,那麼您可以從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的獨立/ Redis的哨兵,但不與Redis的集羣JedisCluster不公開pubsubChannels