Java Code Examples for org.redisson.api.RTopic#addListener()

The following examples show how to use org.redisson.api.RTopic#addListener() . 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: RedisTopicEventChannel.java    From jstarcraft-core with Apache License 2.0 6 votes vote down vote up
@Override
public void registerMonitor(Set<Class> types, EventMonitor monitor) {
    for (Class type : types) {
        EventManager manager = managers.get(type);
        if (manager == null) {
            manager = new EventManager();
            managers.put(type, manager);
            // TODO 需要防止路径冲突
            RTopic topic = getTopic(type);
            EventHandler handler = new EventHandler(type, manager);
            topic.addListener(byte[].class, handler);
            handlers.put(type, handler);
        }
        manager.attachMonitor(monitor);
    }
}
 
Example 2
Source File: RedissonTopicTest.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Test
public void testListenerRemove() throws InterruptedException {
    RedissonClient redisson1 = BaseTest.createInstance();
    RTopic topic1 = redisson1.getTopic("topic");
    int id = topic1.addListener(Message.class, (channel, msg) -> {
        Assert.fail();
    });

    RedissonClient redisson2 = BaseTest.createInstance();
    RTopic topic2 = redisson2.getTopic("topic");
    topic1.removeListener(id);
    topic2.publish(new Message("123"));

    Thread.sleep(1000);

    redisson1.shutdown();
    redisson2.shutdown();
}
 
Example 3
Source File: RedissonTopicTest.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Test
public void test() throws InterruptedException {
    final CountDownLatch messageRecieved = new CountDownLatch(2);

    RedissonClient redisson1 = BaseTest.createInstance();
    RTopic topic1 = redisson1.getTopic("topic");
    topic1.addListener(Message.class, (channel, msg) -> {
        Assert.assertEquals(new Message("123"), msg);
        messageRecieved.countDown();
    });

    RedissonClient redisson2 = BaseTest.createInstance();
    RTopic topic2 = redisson2.getTopic("topic");
    topic2.addListener(Message.class, (channel, msg) -> {
        Assert.assertEquals(new Message("123"), msg);
        messageRecieved.countDown();
    });
    topic2.publish(new Message("123"));

    messageRecieved.await();

    redisson1.shutdown();
    redisson2.shutdown();
}
 
Example 4
Source File: RedissonTopicTest.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Test
public void testLazyUnsubscribe() throws InterruptedException {
    final CountDownLatch messageRecieved = new CountDownLatch(1);

    RedissonClient redisson1 = BaseTest.createInstance();
    RTopic topic1 = redisson1.getTopic("topic");
    int listenerId = topic1.addListener(Message.class, (channel, msg) -> {
        Assert.fail();
    });
    Thread.sleep(1000);
    topic1.removeListener(listenerId);
    Thread.sleep(1000);

    RedissonClient redisson2 = BaseTest.createInstance();
    RTopic topic2 = redisson2.getTopic("topic");
    topic2.addListener(Message.class, (channel, msg) -> {
        Assert.assertEquals(new Message("123"), msg);
        messageRecieved.countDown();
    });
    topic2.publish(new Message("123"));

    Assert.assertTrue(messageRecieved.await(5, TimeUnit.SECONDS));

    redisson1.shutdown();
    redisson2.shutdown();
}
 
Example 5
Source File: RedissonTopicTest.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Test
public void testRemoveByInstance() throws InterruptedException {
    RedissonClient redisson = BaseTest.createInstance();
    RTopic topic1 = redisson.getTopic("topic1");
    MessageListener listener = new MessageListener() {
        @Override
        public void onMessage(CharSequence channel, Object msg) {
            Assert.fail();
        }
    };
    
    topic1.addListener(Message.class, listener);

    topic1 = redisson.getTopic("topic1");
    topic1.removeListener(listener);
    topic1.publish(new Message("123"));

    redisson.shutdown();
}
 
Example 6
Source File: RedissonTopicTest.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Test
public void testRemoveAllListeners2() throws InterruptedException {
    RedissonClient redisson = BaseTest.createInstance();
    RTopic topic1 = redisson.getTopic("topic1");
    AtomicInteger counter = new AtomicInteger();
    
    for (int j = 0; j < 100; j++) {
        for (int i = 0; i < 10; i++) {
            topic1.addListener(Message.class, (channel, msg) -> {
                counter.incrementAndGet();
            });
        }
        
        topic1 = redisson.getTopic("topic1");
        topic1.removeAllListeners();
        topic1.publish(new Message("123"));
    }

    Thread.sleep(1000);
    assertThat(counter.get()).isZero();
    
    redisson.shutdown();
}
 
Example 7
Source File: RedissonTopicTest.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Test
public void testUnsubscribe() throws InterruptedException {
    final CountDownLatch messageRecieved = new CountDownLatch(1);

    RedissonClient redisson = BaseTest.createInstance();
    RTopic topic1 = redisson.getTopic("topic1");
    int listenerId = topic1.addListener(Message.class, (channel, msg) -> {
        Assert.fail();
    });
    topic1.addListener(Message.class, (channel, msg) -> {
        Assert.assertEquals("topic1", channel.toString());
        Assert.assertEquals(new Message("123"), msg);
        messageRecieved.countDown();
    });
    topic1.removeListener(listenerId);

    topic1 = redisson.getTopic("topic1");
    topic1.publish(new Message("123"));

    Assert.assertTrue(messageRecieved.await(5, TimeUnit.SECONDS));

    redisson.shutdown();
}
 
Example 8
Source File: RedissonTopicTest.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Test
public void testSyncCommands() throws InterruptedException {
    RedissonClient redisson = BaseTest.createInstance();
    RTopic topic = redisson.getTopic("system_bus");
    RSet<String> redissonSet = redisson.getSet("set1");
    CountDownLatch latch = new CountDownLatch(1);
    topic.addListener(String.class, (channel, msg) -> {
        for (int j = 0; j < 1000; j++) {
            redissonSet.contains("" + j);
        }
        latch.countDown();
    });
    
    topic.publish("sometext");
    
    latch.await();
    redisson.shutdown();
}
 
Example 9
Source File: RedissonTopicTest.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Test
public void testCountListeners() {
    RedissonClient redisson = BaseTest.createInstance();
    RTopic topic1 = redisson.getTopic("topic", LongCodec.INSTANCE);
    assertThat(topic1.countListeners()).isZero();
    int id = topic1.addListener(Long.class, (channel, msg) -> {
    });
    assertThat(topic1.countListeners()).isOne();

    RTopic topic2 = redisson.getTopic("topic2", LongCodec.INSTANCE);
    assertThat(topic2.countListeners()).isZero();
    int id2 = topic2.addListener(Long.class, (channel, msg) -> {
    });
    assertThat(topic2.countListeners()).isOne();

    topic1.removeListener(id);
    assertThat(topic1.countListeners()).isZero();

    topic2.removeListener(id2);
    assertThat(topic2.countListeners()).isZero();

    redisson.shutdown();
}
 
Example 10
Source File: TopicExamples.java    From redisson-examples with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws InterruptedException {
    // connects to 127.0.0.1:6379 by default
    RedissonClient redisson = Redisson.create();

    CountDownLatch latch = new CountDownLatch(1);
    
    RTopic topic = redisson.getTopic("topic2");
    topic.addListener(String.class, new MessageListener<String>() {
        @Override
        public void onMessage(CharSequence channel, String msg) {
            latch.countDown();
        }
    });
    
    topic.publish("msg");
    latch.await();
    
    redisson.shutdown();
}
 
Example 11
Source File: RedissonPubSubEventStore.java    From j360-boot-app-all with Apache License 2.0 6 votes vote down vote up
public <T extends DispatchEventMessage> void subscribe(PubSubEventType type, final PubSubListener<T> listener, Class<T> clazz) {
    String name = type.toString();
    RTopic topic = redissonSub.getTopic(name);
    int regId = topic.addListener(DispatchEventMessage.class, new MessageListener<DispatchEventMessage>() {
        @Override
        public void onMessage(CharSequence channel, DispatchEventMessage msg) {
            if (!nodeId.equals(msg.getNodeId())) {
                listener.onMessage((T)msg);
            }
        }
    });

    Queue<Integer> list = map.get(name);
    if (list == null) {
        list = new ConcurrentLinkedQueue<Integer>();
        Queue<Integer> oldList = map.putIfAbsent(name, list);
        if (oldList != null) {
            list = oldList;
        }
    }
    list.add(regId);
}
 
Example 12
Source File: DataSubscriberRedisImpl.java    From kkbinlog with Apache License 2.0 6 votes vote down vote up
/**
 * 订阅信息
 *
 * @param clientId
 */
@Override
public void subscribe(String clientId, BinLogDistributorClient binLogDistributorClient) {
    Collection<String> keysByPattern = redissonClient.getKeys().findKeysByPattern(DATA + clientId + "*");
    //处理历史的
    keysByPattern.stream().filter(k -> !k.endsWith("-Lock"))
            .forEach(k -> executors.submit(new DataHandler(k, clientId, binLogDistributorClient, redissonClient)));

    RTopic<String> topic = redissonClient.getTopic(NOTIFIER.concat(clientId));
    topic.addListener((channel, msg) -> {
        //每次推送都会执行这个方法,每次开线程,使用线程里面redis锁判断开销太大,先在外面判断一次
        if (!DataHandler.DATA_KEY_IN_PROCESS.contains(msg)) {
            //如果没在处理再进入
            executors.submit(new DataHandler(msg, clientId, binLogDistributorClient, redissonClient));
        }
    });
}
 
Example 13
Source File: RedissonTopicTest.java    From redisson with Apache License 2.0 5 votes vote down vote up
@Test
public void testCommandsOrdering() throws InterruptedException {
    RedissonClient redisson1 = BaseTest.createInstance();
    RTopic topic1 = redisson1.getTopic("topic", LongCodec.INSTANCE);
    AtomicBoolean stringMessageReceived = new AtomicBoolean();
    topic1.addListener(Long.class, (channel, msg) -> {
        assertThat(msg).isEqualTo(123);
        stringMessageReceived.set(true);
    });
    topic1.publish(123L);

    await().atMost(Duration.ONE_SECOND).untilTrue(stringMessageReceived);

    redisson1.shutdown();
}
 
Example 14
Source File: RedissonTopicTest.java    From redisson with Apache License 2.0 5 votes vote down vote up
@Test
public void testInnerPublish() throws InterruptedException {

    RedissonClient redisson1 = BaseTest.createInstance();
    final RTopic topic1 = redisson1.getTopic("topic1");
    final CountDownLatch messageRecieved = new CountDownLatch(3);
    int listenerId = topic1.addListener(Message.class, (channel, msg) -> {
        Assert.assertEquals(msg, new Message("test"));
        messageRecieved.countDown();
    });

    RedissonClient redisson2 = BaseTest.createInstance();
    final RTopic topic2 = redisson2.getTopic("topic2");
    topic2.addListener(Message.class, (channel, msg) -> {
        messageRecieved.countDown();
        Message m = new Message("test");
        if (!msg.equals(m)) {
            topic1.publish(m);
            topic2.publish(m);
        }
    });
    topic2.publish(new Message("123"));

    Assert.assertTrue(messageRecieved.await(5, TimeUnit.SECONDS));

    redisson1.shutdown();
    redisson2.shutdown();
}
 
Example 15
Source File: RedissonTopicTest.java    From redisson with Apache License 2.0 5 votes vote down vote up
@Test
public void testCountSubscribers() {
    RedissonClient redisson = BaseTest.createInstance();
    RTopic topic1 = redisson.getTopic("topic", LongCodec.INSTANCE);
    assertThat(topic1.countSubscribers()).isZero();
    int id = topic1.addListener(Long.class, (channel, msg) -> {
    });
    assertThat(topic1.countSubscribers()).isOne();
    topic1.removeListener(id);
    assertThat(topic1.countSubscribers()).isZero();

    redisson.shutdown();
}
 
Example 16
Source File: TimeoutTest.java    From redisson with Apache License 2.0 5 votes vote down vote up
public void testPubSub() throws InterruptedException, ExecutionException {
    RTopic topic = redisson.getTopic("simple");
    topic.addListener(String.class, new MessageListener<String>() {
        @Override
        public void onMessage(CharSequence channel, String msg) {
            System.out.println("msg: " + msg);
        }
    });
    for (int i = 0; i < 100; i++) {
        Thread.sleep(1000);
        topic.publish("test" + i);
    }
}
 
Example 17
Source File: RedisPlayground.java    From synapse with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldRetrieveMessagesFromTopic() {
    RTopic topic = redisson.getTopic("test-topic");
    topic.addListener(String.class, (channel, message) -> {
        LOG.info("Received message={} from channel={}", message, channel);
    });
    topic.publish("some message");
    topic.removeAllListeners();
}
 
Example 18
Source File: RedissonTopicTest.java    From redisson with Apache License 2.0 5 votes vote down vote up
@Test
public void testHeavyLoad() throws InterruptedException {
    final CountDownLatch messageRecieved = new CountDownLatch(1000);

    AtomicLong counter = new AtomicLong();
    RedissonClient redisson1 = BaseTest.createInstance();
    RTopic topic1 = redisson1.getTopic("topic");
    topic1.addListener(Message.class, (channel, msg) -> {
        Assert.assertEquals(new Message("123"), msg);
        messageRecieved.countDown();
        counter.incrementAndGet();
    });

    RedissonClient redisson2 = BaseTest.createInstance();
    RTopic topic2 = redisson2.getTopic("topic");
    topic2.addListener(Message.class, (channel, msg) -> {
        Assert.assertEquals(new Message("123"), msg);
        messageRecieved.countDown();
    });

    int count = 10000;
    for (int i = 0; i < count; i++) {
        topic2.publish(new Message("123"));
    }

    messageRecieved.await();

    Thread.sleep(1000);

    Assert.assertEquals(count, counter.get());

    redisson1.shutdown();
    redisson2.shutdown();
}
 
Example 19
Source File: RedissonTopicPatternTest.java    From redisson with Apache License 2.0 4 votes vote down vote up
@Test
public void test() throws InterruptedException {
    final CountDownLatch messageRecieved = new CountDownLatch(5);

    final CountDownLatch statusRecieved = new CountDownLatch(1);
    RedissonClient redisson1 = BaseTest.createInstance();
    RPatternTopic topic1 = redisson1.getPatternTopic("topic.*");
    topic1.addListener(new BasePatternStatusListener() {
        @Override
        public void onPSubscribe(String pattern) {
            Assert.assertEquals("topic.*", pattern);
            statusRecieved.countDown();
        }
    });
    topic1.addListener(Message.class, (pattern, channel, msg) -> {
        Assert.assertEquals(new Message("123"), msg);
        messageRecieved.countDown();
    });

    RedissonClient redisson2 = BaseTest.createInstance();
    RTopic topic2 = redisson2.getTopic("topic.t1");
    topic2.addListener(Message.class, (channel, msg) -> {
        Assert.assertEquals(new Message("123"), msg);
        messageRecieved.countDown();
    });
    topic2.publish(new Message("123"));
    topic2.publish(new Message("123"));

    RTopic topicz = redisson2.getTopic("topicz.t1");
    topicz.publish(new Message("789")); // this message doesn't get
                                        // delivered, and would fail the
                                        // assertion

    RTopic topict2 = redisson2.getTopic("topic.t2");
    topict2.publish(new Message("123"));

    statusRecieved.await();
    Assert.assertTrue(messageRecieved.await(5, TimeUnit.SECONDS));

    redisson1.shutdown();
    redisson2.shutdown();
}
 
Example 20
Source File: RedissonTopicTest.java    From redisson with Apache License 2.0 4 votes vote down vote up
@Test
public void testSubscribeLimit() throws Exception {
    RedisProcess runner = new RedisRunner()
            .port(RedisRunner.findFreePort())
            .nosave()
            .randomDir()
            .run();
    
    int connection = 10;
    int subscription = 5;
    Config config = new Config();
    config.useSingleServer()
            .setAddress("redis://localhost:" + runner.getRedisServerPort())
            .setSubscriptionConnectionPoolSize(connection)
            .setSubscriptionsPerConnection(subscription);
    RedissonClient redissonClient = Redisson.create(config);
    final Queue<RTopic> queue = new LinkedList<>();
    int i = 0;
    boolean timeout = false;
    while (true) {
       try{
          if (timeout) {
              System.out.println("destroy");
              queue.poll().removeAllListeners();
          }
          RTopic topic = redissonClient.getTopic(++i + "");
            topic.addListener(Object.class, new MessageListener<Object>() {
                @Override
                public void onMessage(CharSequence channel, Object msg) {
                    // TODO Auto-generated method stub

                }
            });
          queue.offer(topic);
          if (i > 1000) {
              break;
          }
          System.out.println(i + " - " + queue.size());
       }catch(Exception e){
            timeout = true;
            e.printStackTrace();
       }
    }
    
    redissonClient.shutdown();
    runner.stop();
}