redis.clients.jedis.JedisPubSub Java Examples

The following examples show how to use redis.clients.jedis.JedisPubSub. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RedisClusterMessageTransfer.java    From jmqtt with Apache License 2.0 9 votes vote down vote up
private void subscribe(){
    this.redisTemplate.operate(new RedisCallBack() {
        @Override
        public Object operate(Jedis jedis) {
            jedis.subscribe(new JedisPubSub() {
                @Override
                public void onMessage(String channel, String message) {
                    log.debug("[Cluster] rec message from redis channel:{}",channel);
                    CommandReqOrResp request = new CommandReqOrResp(CommandCode.MESSAGE_CLUSTER_TRANSFER,JSONObject.parseObject(message,
                            Message.class));
                    consumeClusterMessage(request);
                }
            },T_REDIS);
            return null;
        }
    });
}
 
Example #2
Source File: KeyspaceEventsSubscriptorThread.java    From chuidiang-ejemplos with GNU Lesser General Public License v3.0 6 votes vote down vote up
public void run() {
    try (Jedis jedis = Pool.getResource()) {

        jedis.configSet("notify-keyspace-events","KEA");

        jedis.psubscribe(new JedisPubSub() {
            @Override
            public void onPMessage(String pattern, String channel, String message) {
                System.out.println("Keyspace Changes: " + pattern + " " + channel + " " + message);

            }

        }, "__key*__:*");
    } catch (Exception e){
        e.printStackTrace();
    }
}
 
Example #3
Source File: Redis.java    From ymate-platform-v2 with Apache License 2.0 6 votes vote down vote up
@Override
public void destroy() throws Exception {
    if (__inited) {
        __inited = false;
        //
        for (Map.Entry<String, JedisPubSub> _entry : __pubSubs.entrySet()) {
            _entry.getValue().unsubscribe();
        }
        __subscribePool.shutdown();
        __subscribePool = null;
        //
        for (IRedisDataSourceAdapter _adapter : __dataSourceCaches.values()) {
            _adapter.destroy();
        }
        __dataSourceCaches = null;
        __moduleCfg = null;
        __owner = null;
    }
}
 
Example #4
Source File: MessageConsumerRedisImpl.java    From redis_util with Apache License 2.0 6 votes vote down vote up
/**
 *
 * @param redisConnection redis 连接类
 * @param channels 订阅的频道列表
 */
public MessageConsumerRedisImpl(RedisConnection redisConnection, String[] channels) {
    Jedis jedis = null;
    try {
        if (channels != null && channels.length > 0) {
            jedis = redisConnection.getJedis();
            jedis.subscribe(new JedisPubSub() {
                @Override
                public void onMessage(String channel, String message) {
                    System.out.println("receive " + message + " from " + channel);
                    handleMessage(message);
                }
            }, channels);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (jedis != null) {
            jedis.close();
        }
    }
}
 
Example #5
Source File: StandaloneStatMonitor.java    From x-pipe with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("static-access")
@Override
public void run() {
	Thread.currentThread().setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {
		@Override
		public void uncaughtException(Thread arg0, Throwable arg1) {
			logger.error("[error]{}:{}",slaveRedis.getIp(), slaveRedis.getPort(), arg1);
			Cat.logError(arg1);
			redisStatCheckResult.put(slaveRedis, Boolean.FALSE);
			if (null != slave) {
				slave.close();
			}
		}
	});

	logger.debug("[Psubscribe]{}:{}", slaveRedis.getIp(), slaveRedis.getPort());
	slave.psubscribe(new JedisPubSub() {
		@Override
		public void onPMessage(String pattern, String channel, String msg) {
			logger.debug("[OnPMessage]{}:{}", slaveRedis.getIp(), slaveRedis.getPort());
			redisStatCheckResult.put(slaveRedis, Boolean.TRUE);
		}
	}, generateURL(masterRedis.getIp(), masterRedis.getPort()));
}
 
Example #6
Source File: BlackListService.java    From Liudao with GNU General Public License v3.0 6 votes vote down vote up
@PostConstruct
public void init() {
    new Thread() {
        @Override
        public void run() {
            redisDao.subscribe(new JedisPubSub() {
                @Override
                public void onMessage(String pchannel, String message) {
                    logger.info("redis通知,channel={},message={}", pchannel, message);
                    if (channel.equals(pchannel)) {
                        updateCache();
                    }
                }
            }, channel);
        }
    }.start();

    updateCache();
}
 
Example #7
Source File: ConfigService.java    From Liudao with GNU General Public License v3.0 6 votes vote down vote up
@PostConstruct
public void init() {
    new Thread() {
        @Override
        public void run() {
            redisDao.subscribe(new JedisPubSub() {
                @Override
                public void onMessage(String pchannel, String message) {
                    logger.info("redis通知,channel={},message={}", pchannel, message);
                    if (channel.equals(pchannel)) {
                        updateCache();
                    }
                }
            }, channel);
        }
    }.start();

    updateCache();
}
 
Example #8
Source File: JedisUtil.java    From scaffold-cloud with MIT License 5 votes vote down vote up
/**
 * 调用jedis的subscribe()方法
 *
 * @param jedisPubSub
 * @param channels
 */
public static void subscribe(JedisPubSub jedisPubSub, String... channels) {
    Jedis jedis = null;
    try {
        jedis = getResource();
        jedis.subscribe(jedisPubSub, channels);
    } catch (Exception e) {
        logger.warn("psubscribe channels==> {} exception==> {}", channels, e);
    } finally {
        close(jedis);
    }
}
 
Example #9
Source File: SubscriberThread.java    From chuidiang-ejemplos with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void run(){
    try (Jedis jedis = Pool.getResource()) {
        jedis.subscribe(new JedisPubSub() {
            @Override
            public void onMessage(String channel, String message) {
                System.out.println("Subscriber : " + message);
            }
        }, "channel");
    } catch (Exception e){
        e.printStackTrace();
    }
}
 
Example #10
Source File: JedisAdapter.java    From gameserver with Apache License 2.0 5 votes vote down vote up
@Override
public void psubscribe(JedisPubSub jedisPubSub, String... patterns) {
	redis.clients.jedis.Jedis delegate = pool.getResource();
	try {
		delegate.psubscribe(jedisPubSub, patterns);
	} finally {
		pool.returnResource(delegate);
	}
}
 
Example #11
Source File: JedisAdapter.java    From gameserver with Apache License 2.0 5 votes vote down vote up
@Override
public void subscribe(JedisPubSub jedisPubSub, String... channels) {
	redis.clients.jedis.Jedis delegate = pool.getResource();
	try {
		delegate.subscribe(jedisPubSub, channels);
	} finally {
		pool.returnResource(delegate);
	}
}
 
Example #12
Source File: Redis.java    From ymate-platform-v2 with Apache License 2.0 5 votes vote down vote up
@Override
public void subscribe(final String dsName, final JedisPubSub jedisPubSub, final String... channels) {
    String _key = dsName + "@" + jedisPubSub.getClass().getName() + ":" + StringUtils.join(channels, '|');
    if (!__pubSubs.containsKey(_key)) {
        __pubSubs.put(_key, jedisPubSub);
        __subscribePool.execute(new Runnable() {
            @Override
            public void run() {
                while (__inited) {
                    try {
                        openSession(dsName, new IRedisSessionExecutor<Object>() {
                            @Override
                            public Void execute(IRedisSession session) throws Exception {
                                session.getCommandHolder().getJedis().subscribe(jedisPubSub, channels);
                                return null;
                            }
                        });
                    } catch (Exception e) {
                        _LOG.error("Redis connection [" + dsName + "] has been interrupted and is constantly trying to reconnect....", RuntimeUtils.unwrapThrow(e));
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e1) {
                            break;
                        }
                    }
                }
            }
        });
    }
}
 
Example #13
Source File: RedisDao.java    From Liudao with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 订阅给定的一个或多个频道的信息
 *
 * @param jedisPubSub
 * @param channels
 */
public void subscribe(final JedisPubSub jedisPubSub, final String... channels) {
    redisTemplate.execute(new RedisCallback<Object>() {
        @Override
        public Object doInRedis(RedisConnection connection) throws DataAccessException {
            ((Jedis) connection.getNativeConnection()).subscribe(jedisPubSub, channels);
            return null;
        }
    });
}
 
Example #14
Source File: RedisShardSubscription.java    From bazel-buildfarm with Apache License 2.0 5 votes vote down vote up
RedisShardSubscription(
    JedisPubSub subscriber,
    InterruptingRunnable onUnsubscribe,
    Consumer<JedisCluster> onReset,
    Supplier<List<String>> subscriptions,
    RedisClient client) {
  this.subscriber = subscriber;
  this.onUnsubscribe = onUnsubscribe;
  this.onReset = onReset;
  this.subscriptions = subscriptions;
  this.client = client;
}
 
Example #15
Source File: TracingJedisCluster.java    From java-redis-client with Apache License 2.0 5 votes vote down vote up
@Override
public void psubscribe(JedisPubSub jedisPubSub, String... patterns) {
  Span span = helper.buildSpan("psubscribe");
  span.setTag("patterns", Arrays.toString(patterns));
  try {
    super.psubscribe(jedisPubSub, patterns);
  } catch (Exception e) {
    onError(e, span);
    throw e;
  } finally {
    span.finish();
  }
}
 
Example #16
Source File: TracingJedisCluster.java    From java-redis-client with Apache License 2.0 5 votes vote down vote up
@Override
public void subscribe(JedisPubSub jedisPubSub, String... channels) {
  Span span = helper.buildSpan("subscribe");
  span.setTag("channels", Arrays.toString(channels));
  try {
    super.subscribe(jedisPubSub, channels);
  } catch (Exception e) {
    onError(e, span);
    throw e;
  } finally {
    span.finish();
  }
}
 
Example #17
Source File: TracingJedisCluster.java    From java-redis-client with Apache License 2.0 5 votes vote down vote up
@Override
public void subscribe(JedisPubSub jedisPubSub, String... channels) {
  Span span = helper.buildSpan("subscribe");
  span.setTag("channels", Arrays.toString(channels));
  try {
    super.subscribe(jedisPubSub, channels);
  } catch (Exception e) {
    onError(e, span);
    throw e;
  } finally {
    span.finish();
  }
}
 
Example #18
Source File: TracingJedisCluster.java    From java-redis-client with Apache License 2.0 5 votes vote down vote up
@Override
public void psubscribe(JedisPubSub jedisPubSub, String... patterns) {
  Span span = helper.buildSpan("psubscribe");
  span.setTag("patterns", Arrays.toString(patterns));
  try {
    super.psubscribe(jedisPubSub, patterns);
  } catch (Exception e) {
    onError(e, span);
    throw e;
  } finally {
    span.finish();
  }
}
 
Example #19
Source File: SubscriberTest.java    From code with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args){
    Jedis jedis = new Jedis("192.168.108.130" , 6379);
    jedis.subscribe(new JedisPubSub() {
        @Override
        public void onMessage(String channel, String message) {
            System.out.println("receive channel ["+channel+"] message ["+message+"]");
        }
    } , "aliTV" , "googleTV");
}
 
Example #20
Source File: JedisUtil.java    From scaffold-cloud with MIT License 5 votes vote down vote up
/**
 * 调用jedis的psubscribe()方法
 *
 * @param jedisPubSub
 * @param patterns
 */
public static void psubscribe(JedisPubSub jedisPubSub, String... patterns) {
    Jedis jedis = null;
    try {
        jedis = getResource();
        jedis.psubscribe(jedisPubSub, patterns);
    } catch (Exception e) {
        logger.warn("psubscribe patterns==> {} exception==> {}", patterns, e);
    } finally {
        close(jedis);
    }
}
 
Example #21
Source File: EnhancedJedisCluster.java    From super-cloudops with Apache License 2.0 5 votes vote down vote up
@Override
public void subscribe(final JedisPubSub jedisPubSub, final String... channels) {
	new EnhancedJedisClusterCommand<Integer>(connectionHandler, maxAttempts) {
		@Override
		public Integer doExecute(Jedis connection) {
			connection.subscribe(jedisPubSub, channels);
			return 0;
		}
	}.runWithAnyNode();
}
 
Example #22
Source File: EnhancedJedisCluster.java    From super-cloudops with Apache License 2.0 5 votes vote down vote up
@Override
public void psubscribe(final JedisPubSub jedisPubSub, final String... patterns) {
	new EnhancedJedisClusterCommand<Integer>(connectionHandler, maxAttempts) {
		@Override
		public Integer doExecute(Jedis connection) {
			connection.psubscribe(jedisPubSub, patterns);
			return 0;
		}
	}.runWithAnyNode();
}
 
Example #23
Source File: JedisOperator.java    From smart-cache with Apache License 2.0 5 votes vote down vote up
public void subscribe(final JedisPubSub jedisPubSub, final String... channels) {
    execute(new JedisExecutor<Void>() {
        @Override
        Void doInJedis(Jedis jedis) {
            jedis.subscribe(jedisPubSub, channels);
            return null;
        }
    });
}
 
Example #24
Source File: JedisTemplate.java    From smart-cache with Apache License 2.0 5 votes vote down vote up
public void subscribe(final JedisPubSub jedisPubSub, final String... channels) {
    if (cluster) {
        jedisCluster.subscribe(jedisPubSub, channels);
    } else {
        jedisOperator.subscribe(jedisPubSub, channels);
    }
}
 
Example #25
Source File: DefaultRedisPubSub.java    From craft-atom with MIT License 4 votes vote down vote up
DefaultRedisPubSub(JedisPubSub jps) {
	this.jps = jps;
}
 
Example #26
Source File: JedisDummyAdapter.java    From gameserver with Apache License 2.0 4 votes vote down vote up
@Override
public void psubscribe(JedisPubSub jedisPubSub, String... patterns) {
	super.psubscribe(jedisPubSub, patterns);
}
 
Example #27
Source File: JedisDummyAdapter.java    From gameserver with Apache License 2.0 4 votes vote down vote up
@Override
public void subscribe(JedisPubSub jedisPubSub, String... channels) {
	super.subscribe(jedisPubSub, channels);
}
 
Example #28
Source File: Redis.java    From ymate-platform-v2 with Apache License 2.0 4 votes vote down vote up
@Override
public void subscribe(JedisPubSub jedisPubSub, String... channels) {
    subscribe(__moduleCfg.getDataSourceDefaultName(), jedisPubSub, channels);
}
 
Example #29
Source File: LatencyTest.java    From x-pipe with Apache License 2.0 4 votes vote down vote up
private void startRead(String keyPrefix) {
    if (!readStarted.compareAndSet(false, true)) {
        System.out.println("Read already started!");
        return;
    }

    if (keyPrefix == null || keyPrefix.trim().equals("")) {
        keyPrefix = defaultKeyPrefix;
    }

    System.out.println(String.format("Start reading %d records with keyPrefix: %s", total, keyPrefix));

    final String finalKeyPrefix = keyPrefix;
    final AtomicLong totalDelay = new AtomicLong();
    final AtomicLong counter = new AtomicLong();
    final SettableFuture<Boolean> readCompleted = SettableFuture.create();

    executorService.submit(new Runnable() {
        @Override
        public void run() {
            try {
                readCompleted.get();
                double avgDelay = (double) totalDelay.get() / (double) (total);
                System.out.println(String.format("Read completed, average delay is: %s ms", decimalFormat.format
                        (avgDelay)));
            } catch (Throwable ex) {
                ex.printStackTrace();
            }
        }
    });

    executorService.submit(new Runnable() {
        @Override
        public void run() {
            final Jedis slaveJedis = createJedis("localhost", 6379);
            slaveJedis.psubscribe(new JedisPubSub() {
                @Override
                public void onPMessage(String pattern, String channel, String message) {
                    totalDelay.addAndGet(System.currentTimeMillis() - Long.valueOf(message));
                    long current = counter.incrementAndGet();
                    if (current != 0 && current % countIndicator == 0) {
                        System.out.println(String.format("%d records read", current));
                    }
                    if (current >= total) {
                        readCompleted.set(true);
                    }
                }
            }, String.format("%s*", finalKeyPrefix));
        }
    });
}
 
Example #30
Source File: RedisShardSubscription.java    From bazel-buildfarm with Apache License 2.0 4 votes vote down vote up
public JedisPubSub getSubscriber() {
  return subscriber;
}