1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
| public static void pubSub() { RedisURI redisURI = RedisURI.builder() .withHost("localhost") .withPort(6379) .withTimeout(Duration.of(1, ChronoUnit.SECONDS)) .build(); RedisClient redisClient = RedisClient.create(redisURI);
StatefulRedisPubSubConnection<String, String> redisPubSubConnection = redisClient.connectPubSub(); redisPubSubConnection.addListener(new RedisPubSubListener<String, String>() { @Override public void message(String channel, String message) { System.out.println(String.format("Channel:%s,Message:%s", channel, message)); }
@Override public void message(String pattern, String channel, String message) {
}
@Override public void subscribed(String channel, long count) {
}
@Override public void psubscribed(String pattern, long count) {
}
@Override public void unsubscribed(String channel, long count) {
}
@Override public void punsubscribed(String pattern, long count) {
} }); redisPubSubConnection.sync().subscribe("dev:msg_channel");
StatefulRedisConnection<String, String> connect = redisClient.connect(); for (int i = 0; i < 10; i++) { connect.sync().publish("dev:msg_channel", "message_" + i); }
connect.close(); redisPubSubConnection.close(); redisClient.shutdown(); }
|