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();
}
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;
}
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);
}
}
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);
}
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());
}
}
}
Aggregations