Search in sources :

Example 6 with MessageListener

use of org.redisson.api.listener.MessageListener in project redisson by redisson.

the class RedissonTopicTest method testRemoveByInstance.

@Test
public void testRemoveByInstance() throws InterruptedException {
    RedissonClient redisson = BaseTest.createInstance();
    RTopic<Message> topic1 = redisson.getTopic("topic1");
    MessageListener listener = new MessageListener() {

        @Override
        public void onMessage(String channel, Object msg) {
            Assert.fail();
        }
    };
    topic1.addListener(listener);
    topic1 = redisson.getTopic("topic1");
    topic1.removeListener(listener);
    topic1.publish(new Message("123"));
    redisson.shutdown();
}
Also used : RedissonClient(org.redisson.api.RedissonClient) MessageListener(org.redisson.api.listener.MessageListener) Test(org.junit.Test)

Example 7 with MessageListener

use of org.redisson.api.listener.MessageListener in project redisson by redisson.

the class RedissonExecutorService method awaitTermination.

@Override
public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
    if (isTerminated()) {
        return true;
    }
    final CountDownLatch latch = new CountDownLatch(1);
    MessageListener<Integer> listener = new MessageListener<Integer>() {

        @Override
        public void onMessage(String channel, Integer msg) {
            if (msg == TERMINATED_STATE) {
                latch.countDown();
            }
        }
    };
    int listenerId = terminationTopic.addListener(listener);
    if (isTerminated()) {
        terminationTopic.removeListener(listenerId);
        return true;
    }
    boolean res = latch.await(timeout, unit);
    terminationTopic.removeListener(listenerId);
    return res;
}
Also used : MessageListener(org.redisson.api.listener.MessageListener) CountDownLatch(java.util.concurrent.CountDownLatch)

Example 8 with MessageListener

use of org.redisson.api.listener.MessageListener in project redisson by redisson.

the class RedissonSessionManager method stopInternal.

@Override
protected void stopInternal() throws LifecycleException {
    super.stopInternal();
    setState(LifecycleState.STOPPING);
    Pipeline pipeline = getContext().getPipeline();
    synchronized (pipeline) {
        if (readMode == ReadMode.REDIS) {
            Arrays.stream(pipeline.getValves()).filter(v -> v.getClass() == UsageValve.class).forEach(v -> {
                if (((UsageValve) v).decUsage() == 0) {
                    pipeline.removeValve(v);
                }
            });
        }
        if (updateMode == UpdateMode.AFTER_REQUEST) {
            Arrays.stream(pipeline.getValves()).filter(v -> v.getClass() == UpdateValve.class).forEach(v -> {
                if (((UpdateValve) v).decUsage() == 0) {
                    pipeline.removeValve(v);
                }
            });
        }
    }
    if (messageListener != null) {
        RTopic updatesTopic = getTopic();
        updatesTopic.removeListener(messageListener);
    }
    codecToUse = null;
    try {
        shutdownRedisson();
    } catch (Exception e) {
        throw new LifecycleException(e);
    }
}
Also used : HttpSession(javax.servlet.http.HttpSession) java.util(java.util) Codec(org.redisson.client.codec.Codec) StringCodec(org.redisson.client.codec.StringCodec) ManagerBase(org.apache.catalina.session.ManagerBase) Config(org.redisson.config.Config) RTopic(org.redisson.api.RTopic) RSet(org.redisson.api.RSet) IOException(java.io.IOException) Log(org.apache.juli.logging.Log) LogFactory(org.apache.juli.logging.LogFactory) File(java.io.File) Redisson(org.redisson.Redisson) RMap(org.redisson.api.RMap) CompositeCodec(org.redisson.codec.CompositeCodec) org.apache.catalina(org.apache.catalina) RedissonClient(org.redisson.api.RedissonClient) MessageListener(org.redisson.api.listener.MessageListener) RTopic(org.redisson.api.RTopic) IOException(java.io.IOException)

Example 9 with MessageListener

use of org.redisson.api.listener.MessageListener in project redisson by redisson.

the class RedissonSessionManager method startInternal.

@Override
protected void startInternal() throws LifecycleException {
    super.startInternal();
    redisson = buildClient();
    final ClassLoader applicationClassLoader;
    if (getContext().getLoader().getClassLoader() != null) {
        applicationClassLoader = getContext().getLoader().getClassLoader();
    } else if (Thread.currentThread().getContextClassLoader() != null) {
        applicationClassLoader = Thread.currentThread().getContextClassLoader();
    } else {
        applicationClassLoader = getClass().getClassLoader();
    }
    Codec codec = redisson.getConfig().getCodec();
    try {
        codecToUse = codec.getClass().getConstructor(ClassLoader.class, codec.getClass()).newInstance(applicationClassLoader, codec);
    } catch (Exception e) {
        throw new LifecycleException(e);
    }
    Pipeline pipeline = getContext().getPipeline();
    synchronized (pipeline) {
        if (readMode == ReadMode.REDIS) {
            Optional<Valve> res = Arrays.stream(pipeline.getValves()).filter(v -> v.getClass() == UsageValve.class).findAny();
            if (res.isPresent()) {
                ((UsageValve) res.get()).incUsage();
            } else {
                pipeline.addValve(new UsageValve());
            }
        }
        if (updateMode == UpdateMode.AFTER_REQUEST) {
            Optional<Valve> res = Arrays.stream(pipeline.getValves()).filter(v -> v.getClass() == UpdateValve.class).findAny();
            if (res.isPresent()) {
                ((UpdateValve) res.get()).incUsage();
            } else {
                pipeline.addValve(new UpdateValve());
            }
        }
    }
    if (readMode == ReadMode.MEMORY && this.broadcastSessionUpdates || broadcastSessionEvents) {
        RTopic updatesTopic = getTopic();
        messageListener = new MessageListener<AttributeMessage>() {

            @Override
            public void onMessage(CharSequence channel, AttributeMessage msg) {
                try {
                    if (msg.getNodeId().equals(nodeId)) {
                        return;
                    }
                    RedissonSession session = (RedissonSession) RedissonSessionManager.super.findSession(msg.getSessionId());
                    if (session != null) {
                        if (msg instanceof SessionDestroyedMessage) {
                            session.expire();
                        }
                        if (msg instanceof AttributeRemoveMessage) {
                            for (String name : ((AttributeRemoveMessage) msg).getNames()) {
                                session.superRemoveAttributeInternal(name, true);
                            }
                        }
                        if (msg instanceof AttributesClearMessage) {
                            RedissonSessionManager.super.remove(session, false);
                        }
                        if (msg instanceof AttributesPutAllMessage) {
                            AttributesPutAllMessage m = (AttributesPutAllMessage) msg;
                            Map<String, Object> attrs = m.getAttrs(codecToUse.getMapValueDecoder());
                            session.load(attrs);
                        }
                        if (msg instanceof AttributeUpdateMessage) {
                            AttributeUpdateMessage m = (AttributeUpdateMessage) msg;
                            session.superSetAttribute(m.getName(), m.getValue(codecToUse.getMapValueDecoder()), true);
                        }
                    } else {
                        if (msg instanceof SessionCreatedMessage) {
                            Session s = findSession(msg.getSessionId());
                            if (s == null) {
                                throw new IllegalStateException("Unable to find session: " + msg.getSessionId());
                            }
                        }
                        if (msg instanceof SessionDestroyedMessage) {
                            Session s = findSession(msg.getSessionId(), false);
                            if (s == null) {
                                throw new IllegalStateException("Unable to find session: " + msg.getSessionId());
                            }
                            s.expire();
                            RSet<String> set = getNotifiedNodes(msg.getSessionId());
                            set.add(nodeId);
                        }
                    }
                } catch (Exception e) {
                    log.error("Unable to handle topic message", e);
                }
            }
        };
        updatesTopic.addListener(AttributeMessage.class, messageListener);
    }
    setState(LifecycleState.STARTING);
}
Also used : HttpSession(javax.servlet.http.HttpSession) java.util(java.util) Codec(org.redisson.client.codec.Codec) StringCodec(org.redisson.client.codec.StringCodec) ManagerBase(org.apache.catalina.session.ManagerBase) Config(org.redisson.config.Config) RTopic(org.redisson.api.RTopic) RSet(org.redisson.api.RSet) IOException(java.io.IOException) Log(org.apache.juli.logging.Log) LogFactory(org.apache.juli.logging.LogFactory) File(java.io.File) Redisson(org.redisson.Redisson) RMap(org.redisson.api.RMap) CompositeCodec(org.redisson.codec.CompositeCodec) org.apache.catalina(org.apache.catalina) RedissonClient(org.redisson.api.RedissonClient) MessageListener(org.redisson.api.listener.MessageListener) Codec(org.redisson.client.codec.Codec) StringCodec(org.redisson.client.codec.StringCodec) CompositeCodec(org.redisson.codec.CompositeCodec) RSet(org.redisson.api.RSet) IOException(java.io.IOException) RTopic(org.redisson.api.RTopic) RMap(org.redisson.api.RMap) HttpSession(javax.servlet.http.HttpSession)

Example 10 with MessageListener

use of org.redisson.api.listener.MessageListener in project redisson by redisson.

the class LocalCacheListener method add.

public void add(Map<?, ?> cache) {
    this.cache = cache;
    invalidationTopic = RedissonTopic.createRaw(LocalCachedMessageCodec.INSTANCE, commandExecutor, getInvalidationTopicName());
    if (options.getReconnectionStrategy() != ReconnectionStrategy.NONE) {
        reconnectionListenerId = invalidationTopic.addListener(new BaseStatusListener() {

            @Override
            public void onSubscribe(String channel) {
                if (options.getReconnectionStrategy() == ReconnectionStrategy.CLEAR) {
                    cache.clear();
                }
                if (options.getReconnectionStrategy() == ReconnectionStrategy.LOAD && // check if instance has already been used
                lastInvalidate > 0) {
                    loadAfterReconnection();
                }
            }
        });
    }
    if (options.getSyncStrategy() != SyncStrategy.NONE) {
        syncListenerId = invalidationTopic.addListener(Object.class, new MessageListener<Object>() {

            @Override
            public void onMessage(CharSequence channel, Object msg) {
                if (msg instanceof LocalCachedMapDisable) {
                    LocalCachedMapDisable m = (LocalCachedMapDisable) msg;
                    String requestId = m.getRequestId();
                    Set<CacheKey> keysToDisable = new HashSet<CacheKey>();
                    for (byte[] keyHash : ((LocalCachedMapDisable) msg).getKeyHashes()) {
                        CacheKey key = new CacheKey(keyHash);
                        keysToDisable.add(key);
                    }
                    disableKeys(requestId, keysToDisable, m.getTimeout());
                    RedissonTopic topic = RedissonTopic.createRaw(LocalCachedMessageCodec.INSTANCE, commandExecutor, RedissonObject.suffixName(name, requestId + DISABLED_ACK_SUFFIX));
                    topic.publishAsync(new LocalCachedMapDisableAck());
                }
                if (msg instanceof LocalCachedMapEnable) {
                    LocalCachedMapEnable m = (LocalCachedMapEnable) msg;
                    for (byte[] keyHash : m.getKeyHashes()) {
                        CacheKey key = new CacheKey(keyHash);
                        disabledKeys.remove(key, m.getRequestId());
                    }
                }
                if (msg instanceof LocalCachedMapClear) {
                    LocalCachedMapClear clearMsg = (LocalCachedMapClear) msg;
                    if (!Arrays.equals(clearMsg.getExcludedId(), instanceId)) {
                        cache.clear();
                        if (clearMsg.isReleaseSemaphore()) {
                            RSemaphore semaphore = getClearSemaphore(clearMsg.getRequestId());
                            semaphore.releaseAsync();
                        }
                    }
                }
                if (msg instanceof LocalCachedMapInvalidate) {
                    LocalCachedMapInvalidate invalidateMsg = (LocalCachedMapInvalidate) msg;
                    if (!Arrays.equals(invalidateMsg.getExcludedId(), instanceId)) {
                        for (byte[] keyHash : invalidateMsg.getKeyHashes()) {
                            CacheKey key = new CacheKey(keyHash);
                            cache.remove(key);
                        }
                    }
                }
                if (msg instanceof LocalCachedMapUpdate) {
                    LocalCachedMapUpdate updateMsg = (LocalCachedMapUpdate) msg;
                    if (!Arrays.equals(updateMsg.getExcludedId(), instanceId)) {
                        for (LocalCachedMapUpdate.Entry entry : updateMsg.getEntries()) {
                            ByteBuf keyBuf = Unpooled.wrappedBuffer(entry.getKey());
                            ByteBuf valueBuf = Unpooled.wrappedBuffer(entry.getValue());
                            try {
                                updateCache(keyBuf, valueBuf);
                            } catch (IOException e) {
                                log.error("Can't decode map entry", e);
                            } finally {
                                keyBuf.release();
                                valueBuf.release();
                            }
                        }
                    }
                }
                if (options.getReconnectionStrategy() == ReconnectionStrategy.LOAD) {
                    lastInvalidate = System.currentTimeMillis();
                }
            }
        });
        String disabledKeysName = RedissonObject.suffixName(name, DISABLED_KEYS_SUFFIX);
        RListMultimapCache<LocalCachedMapDisabledKey, String> multimap = new RedissonListMultimapCache<LocalCachedMapDisabledKey, String>(null, codec, commandExecutor, disabledKeysName);
        for (LocalCachedMapDisabledKey key : multimap.readAllKeySet()) {
            Set<CacheKey> keysToDisable = new HashSet<CacheKey>();
            for (String hash : multimap.getAll(key)) {
                CacheKey cacheKey = new CacheKey(ByteBufUtil.decodeHexDump(hash));
                keysToDisable.add(cacheKey);
            }
            disableKeys(key.getRequestId(), keysToDisable, key.getTimeout());
        }
    }
}
Also used : MessageListener(org.redisson.api.listener.MessageListener) IOException(java.io.IOException) ByteBuf(io.netty.buffer.ByteBuf) BaseStatusListener(org.redisson.api.listener.BaseStatusListener)

Aggregations

MessageListener (org.redisson.api.listener.MessageListener)12 Test (org.junit.jupiter.api.Test)4 RTopic (org.redisson.api.RTopic)4 IOException (java.io.IOException)3 RedissonClient (org.redisson.api.RedissonClient)3 CompositeCodec (org.redisson.codec.CompositeCodec)3 File (java.io.File)2 java.util (java.util)2 HttpSession (javax.servlet.http.HttpSession)2 org.apache.catalina (org.apache.catalina)2 ManagerBase (org.apache.catalina.session.ManagerBase)2 Log (org.apache.juli.logging.Log)2 LogFactory (org.apache.juli.logging.LogFactory)2 Redisson (org.redisson.Redisson)2 RMap (org.redisson.api.RMap)2 RSet (org.redisson.api.RSet)2 RTopicReactive (org.redisson.api.RTopicReactive)2 RTopicRx (org.redisson.api.RTopicRx)2 BaseStatusListener (org.redisson.api.listener.BaseStatusListener)2 Codec (org.redisson.client.codec.Codec)2