org.redisson.api.RTopic Java Examples

The following examples show how to use org.redisson.api.RTopic. 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: 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 #2
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 #3
Source File: SpringNamespaceObjectTest.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Test
public void testRObjects() {
    Object bean = context.getBean(key);
    assertTrue(cls.isInstance(bean));
    if (RObject.class.isAssignableFrom(cls)) {
        assertEquals(parentKey == null ? key : parentKey, RObject.class.cast(bean).getName());
    }
    if (RTopic.class.isAssignableFrom(cls)) {
        assertEquals(key, RTopic.class.cast(bean).getChannelNames().get(0));
    }
    if (RPatternTopic.class.isAssignableFrom(cls)) {
        assertEquals(key, RPatternTopic.class.cast(bean).getPatternNames().get(0));
    }
    if (RLiveObject.class.isAssignableFrom(cls)) {
        assertEquals(key, RLiveObject.class.cast(bean).getLiveObjectId());
    }
}
 
Example #4
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 #5
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 #6
Source File: RedissonTopicTest.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Test
public void testRemoveAllListeners() throws InterruptedException {
    RedissonClient redisson = BaseTest.createInstance();
    RTopic topic1 = redisson.getTopic("topic1");
    AtomicInteger counter = new AtomicInteger();
    
    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: RedissonMapCache.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Override
public void removeListener(int listenerId) {
    super.removeListener(listenerId);
    
    RTopic removedTopic = redisson.getTopic(getRemovedChannelName());
    removedTopic.removeListener(listenerId);

    RTopic createdTopic = redisson.getTopic(getCreatedChannelName());
    createdTopic.removeListener(listenerId);

    RTopic updatedTopic = redisson.getTopic(getUpdatedChannelName());
    updatedTopic.removeListener(listenerId);

    RTopic expiredTopic = redisson.getTopic(getExpiredChannelName());
    expiredTopic.removeListener(listenerId);
}
 
Example #8
Source File: RedissonSessionRepository.java    From redisson with Apache License 2.0 6 votes vote down vote up
RedissonSession() {
    this.delegate = new MapSession();
    map = redisson.getMap(keyPrefix + delegate.getId(), new CompositeCodec(StringCodec.INSTANCE, redisson.getConfig().getCodec()));

    Map<String, Object> newMap = new HashMap<String, Object>(3);
    newMap.put("session:creationTime", delegate.getCreationTime().toEpochMilli());
    newMap.put("session:lastAccessedTime", delegate.getLastAccessedTime().toEpochMilli());
    newMap.put("session:maxInactiveInterval", delegate.getMaxInactiveInterval().getSeconds());
    map.putAll(newMap);

    updateExpiration();
    
    String channelName = getEventsChannelName(delegate.getId());
    RTopic topic = redisson.getTopic(channelName, StringCodec.INSTANCE);
    topic.publish(delegate.getId());
}
 
Example #9
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 #10
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 #11
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 #12
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 #13
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 #14
Source File: RedissionUtilsTest.java    From Redis_Learning with Apache License 2.0 6 votes vote down vote up
/** 
     * ��Ϣ���еĶ����� 
     * @throws InterruptedException 
     */  
    @Test  
    public void testGetRTopicSub() throws InterruptedException {  
        RTopic<String> rTopic=RedissionUtils.getInstance().getRTopic(redisson, "testTopic");  
//        rTopic.addListener(new MessageListener<String>() {  
//
//			@Override
//			public void onMessage(String arg0, String arg1) {
//				System.out.println("�㷢������:"+arg0);
//			}  
//        });  
        //�ȴ������߷�����Ϣ  
        RCountDownLatch rCountDownLatch=RedissionUtils.getInstance().getRCountDownLatch(redisson, "testCountDownLatch");  
        rCountDownLatch.trySetCount(1);  
        rCountDownLatch.await();  
    }
 
Example #15
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 #16
Source File: RedisTopicEventChannel.java    From jstarcraft-core with Apache License 2.0 6 votes vote down vote up
@Override
public void unregisterMonitor(Set<Class> types, EventMonitor monitor) {
    for (Class type : types) {
        EventManager manager = managers.get(type);
        if (manager != null) {
            manager.detachMonitor(monitor);
            if (manager.getSize() == 0) {
                managers.remove(type);
                // TODO 需要防止路径冲突
                RTopic topic = getTopic(type);
                EventHandler handler = handlers.remove(type);
                topic.removeListener(handler);
            }
        }
    }
}
 
Example #17
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 #18
Source File: RedissonTopicPatternTest.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Test
public void testListenerRemove() throws InterruptedException {
    RedissonClient redisson1 = BaseTest.createInstance();
    RPatternTopic topic1 = redisson1.getPatternTopic("topic.*");
    final CountDownLatch l = new CountDownLatch(1);
    topic1.addListener(new BasePatternStatusListener() {
        @Override
        public void onPUnsubscribe(String pattern) {
            Assert.assertEquals("topic.*", pattern);
            l.countDown();
        }
    });
    int id = topic1.addListener(Message.class, (pattern, channel, msg) -> {
        Assert.fail();
    });

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

    redisson1.shutdown();
    redisson2.shutdown();
}
 
Example #19
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 #20
Source File: RedissonSessionManager.java    From redisson with Apache License 2.0 5 votes vote down vote up
@Override
protected void stopInternal() throws LifecycleException {
    super.stopInternal();
    
    setState(LifecycleState.STOPPING);
    
    Pipeline pipeline = getEngine().getPipeline();
    synchronized (pipeline) {
        contextInUse.remove(((Context) getContainer()).getName());
        //remove valves when all of the RedissonSessionManagers (web apps) are not in use anymore
        if (contextInUse.isEmpty()) {
            if (updateValve != null) {
                pipeline.removeValve(updateValve);
                updateValve = null;
            }
        }
    }
    
    if (messageListener != null) {
         RTopic updatesTopic = getTopic();
         updatesTopic.removeListener(messageListener);
    }

    codecToUse = null;

    try {
        shutdownRedisson();
    } catch (Exception e) {
        throw new LifecycleException(e);
    }
    
}
 
Example #21
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 #22
Source File: RedissonTopicPatternTest.java    From redisson with Apache License 2.0 5 votes vote down vote up
@Test
public void testLazyUnsubscribe() throws InterruptedException {
    final CountDownLatch messageRecieved = new CountDownLatch(1);

    RedissonClient redisson1 = BaseTest.createInstance();
    RPatternTopic topic1 = redisson1.getPatternTopic("topic.*");
    int listenerId = topic1.addListener(Message.class, (pattern, channel, msg) -> {
        Assert.fail();
    });

    Thread.sleep(1000);
    topic1.removeListener(listenerId);
    Thread.sleep(1000);

    RedissonClient redisson2 = BaseTest.createInstance();
    RPatternTopic topic2 = redisson2.getPatternTopic("topic.*");
    topic2.addListener(Message.class, (pattern, channel, msg) -> {
        Assert.assertTrue(pattern.equals("topic.*"));
        Assert.assertTrue(channel.equals("topic.t1"));
        Assert.assertEquals(new Message("123"), msg);
        messageRecieved.countDown();
    });

    RTopic topic3 = redisson2.getTopic("topic.t1");
    topic3.publish(new Message("123"));

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

    redisson1.shutdown();
    redisson2.shutdown();
}
 
Example #23
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 #24
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 #25
Source File: RedissonSessionManager.java    From redisson with Apache License 2.0 5 votes vote down vote up
@Override
protected void stopInternal() throws LifecycleException {
    super.stopInternal();
    
    setState(LifecycleState.STOPPING);
    
    Pipeline pipeline = getEngine().getPipeline();
    synchronized (pipeline) {
        contextInUse.remove(getContext().getName());
        //remove valves when all of the RedissonSessionManagers (web apps) are not in use anymore
        if (contextInUse.isEmpty()) {
            if (updateValve != null) {
                pipeline.removeValve(updateValve);
                updateValve = null;
            }
        }
    }
    
    if (messageListener != null) {
         RTopic updatesTopic = getTopic();
         updatesTopic.removeListener(messageListener);
    }

    codecToUse = null;

    try {
        shutdownRedisson();
    } catch (Exception e) {
        throw new LifecycleException(e);
    }
    
}
 
Example #26
Source File: RedissonSessionManager.java    From redisson with Apache License 2.0 5 votes vote down vote up
@Override
protected void stopInternal() throws LifecycleException {
    super.stopInternal();
    
    setState(LifecycleState.STOPPING);
    
    Pipeline pipeline = getEngine().getPipeline();
    synchronized (pipeline) {
        contextInUse.remove(getContext().getName());
        //remove valves when all of the RedissonSessionManagers (web apps) are not in use anymore
        if (contextInUse.isEmpty()) {
            if (updateValve != null) {
                pipeline.removeValve(updateValve);
                updateValve = null;
            }
        }
    }
    
    if (messageListener != null) {
         RTopic updatesTopic = getTopic();
         updatesTopic.removeListener(messageListener);
    }

    codecToUse = null;

    try {
        shutdownRedisson();
    } catch (Exception e) {
        throw new LifecycleException(e);
    }
    
}
 
Example #27
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 #28
Source File: MQAop.java    From redisson-spring-boot-starter with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Around("aspect(mq)")
public Object aroundAdvice(ProceedingJoinPoint proceedingJoinPoint, MQPublish mq) {
    try {
        Object obj = proceedingJoinPoint.proceed();
        RTopic topic = redissonClient.getTopic(mq.name());
        topic.publish(obj);
        return obj;
    } catch (Throwable e) {
        throw new RuntimeException(e);
    }

}
 
Example #29
Source File: DataPublisherRedisImpl.java    From kkbinlog with Apache License 2.0 5 votes vote down vote up
public void doPublish(String clientId, String dataKey, EventBaseDTO data) {
    RQueue<EventBaseDTO> dataList = redissonClient.getQueue(dataKey);
    boolean result = dataList.offer(data);
    log.info("推送结果{},推送信息,{}",result, data);
    String notifier = NOTIFIER.concat(clientId);
    RTopic<String> rTopic = redissonClient.getTopic(notifier);
    rTopic.publish(dataKey);
}
 
Example #30
Source File: RedisTopicEventChannel.java    From jstarcraft-core with Apache License 2.0 5 votes vote down vote up
protected RTopic getTopic(Class type) {
    RTopic topic = topics.get(type);
    if (topic == null) {
        topic = redisson.getTopic(name + StringUtility.DOT + type.getName(), byteCodec);
        topics.put(type, topic);
    }
    return topic;
}