Search in sources :

Example 21 with Codec

use of org.redisson.client.codec.Codec in project redisson by redisson.

the class RedissonReactiveSubscription method pUnsubscribe.

@Override
public Mono<Void> pUnsubscribe(ByteBuffer... patterns) {
    monosListener.acquire();
    return Mono.defer(() -> {
        List<CompletableFuture<?>> futures = new ArrayList<>(patterns.length);
        for (ByteBuffer channel : patterns) {
            ChannelName cn = toChannelName(channel);
            CompletableFuture<Codec> f = subscribeService.unsubscribe(cn, PubSubType.PUNSUBSCRIBE);
            f = f.whenComplete((res, e) -> {
                synchronized (RedissonReactiveSubscription.this.patterns) {
                    Collection<PubSubConnectionEntry> entries = RedissonReactiveSubscription.this.patterns.get(cn);
                    entries.stream().filter(en -> en.hasListeners(cn)).forEach(ee -> RedissonReactiveSubscription.this.patterns.remove(cn));
                }
            });
            futures.add(f);
        }
        CompletableFuture<Void> future = CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]));
        future = future.whenComplete((r, e) -> {
            monosListener.release();
        });
        return Mono.fromFuture(future);
    });
}
Also used : PubSubType(org.redisson.client.protocol.pubsub.PubSubType) PublishSubscribeService(org.redisson.pubsub.PublishSubscribeService) java.util(java.util) Disposable(reactor.core.Disposable) Codec(org.redisson.client.codec.Codec) PubSubConnectionEntry(org.redisson.pubsub.PubSubConnectionEntry) ConnectionManager(org.redisson.connection.ConnectionManager) ByteArrayCodec(org.redisson.client.codec.ByteArrayCodec) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Mono(reactor.core.publisher.Mono) CompletableFuture(java.util.concurrent.CompletableFuture) AtomicReference(java.util.concurrent.atomic.AtomicReference) Collectors(java.util.stream.Collectors) ByteBuffer(java.nio.ByteBuffer) StandardCharsets(java.nio.charset.StandardCharsets) RedisPubSubListener(org.redisson.client.RedisPubSubListener) SubscriptionListener(org.springframework.data.redis.connection.SubscriptionListener) BaseRedisPubSubListener(org.redisson.client.BaseRedisPubSubListener) Flux(reactor.core.publisher.Flux) ReactiveSubscription(org.springframework.data.redis.connection.ReactiveSubscription) Entry(java.util.Map.Entry) ChannelName(org.redisson.client.ChannelName) CompletableFuture(java.util.concurrent.CompletableFuture) Codec(org.redisson.client.codec.Codec) ByteArrayCodec(org.redisson.client.codec.ByteArrayCodec) ChannelName(org.redisson.client.ChannelName) ByteBuffer(java.nio.ByteBuffer)

Example 22 with Codec

use of org.redisson.client.codec.Codec 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 23 with Codec

use of org.redisson.client.codec.Codec in project redisson by redisson.

the class CommandAsyncService method evalAsync.

private <T, R> RFuture<R> evalAsync(NodeSource nodeSource, boolean readOnlyMode, Codec codec, RedisCommand<T> evalCommandType, String script, List<Object> keys, boolean noRetry, Object... params) {
    if (isEvalCacheActive() && evalCommandType.getName().equals("EVAL")) {
        CompletableFuture<R> mainPromise = new CompletableFuture<>();
        Object[] pps = copy(params);
        CompletableFuture<R> promise = new CompletableFuture<>();
        String sha1 = calcSHA(script);
        RedisCommand cmd;
        if (readOnlyMode && evalShaROSupported.get()) {
            cmd = new RedisCommand(evalCommandType, "EVALSHA_RO");
        } else {
            cmd = new RedisCommand(evalCommandType, "EVALSHA");
        }
        List<Object> args = new ArrayList<Object>(2 + keys.size() + params.length);
        args.add(sha1);
        args.add(keys.size());
        args.addAll(keys);
        args.addAll(Arrays.asList(params));
        RedisExecutor<T, R> executor = new RedisExecutor<>(readOnlyMode, nodeSource, codec, cmd, args.toArray(), promise, false, connectionManager, objectBuilder, referenceType, noRetry);
        executor.execute();
        promise.whenComplete((res, e) -> {
            if (e != null) {
                if (e.getMessage().startsWith("ERR unknown command")) {
                    evalShaROSupported.set(false);
                    free(pps);
                    RFuture<R> future = evalAsync(nodeSource, readOnlyMode, codec, evalCommandType, script, keys, noRetry, params);
                    transfer(future.toCompletableFuture(), mainPromise);
                } else if (e.getMessage().startsWith("NOSCRIPT")) {
                    RFuture<String> loadFuture = loadScript(executor.getRedisClient(), script);
                    loadFuture.whenComplete((r, ex) -> {
                        if (ex != null) {
                            free(pps);
                            mainPromise.completeExceptionally(ex);
                            return;
                        }
                        List<Object> newargs = new ArrayList<Object>(2 + keys.size() + params.length);
                        newargs.add(sha1);
                        newargs.add(keys.size());
                        newargs.addAll(keys);
                        newargs.addAll(Arrays.asList(pps));
                        NodeSource ns = nodeSource;
                        if (ns.getRedisClient() == null) {
                            ns = new NodeSource(nodeSource, executor.getRedisClient());
                        }
                        RFuture<R> future = async(readOnlyMode, ns, codec, cmd, newargs.toArray(), false, noRetry);
                        transfer(future.toCompletableFuture(), mainPromise);
                    });
                } else {
                    free(pps);
                    mainPromise.completeExceptionally(e);
                }
                return;
            }
            free(pps);
            mainPromise.complete(res);
        });
        return new CompletableFutureWrapper<>(mainPromise);
    }
    List<Object> args = new ArrayList<Object>(2 + keys.size() + params.length);
    args.add(script);
    args.add(keys.size());
    args.addAll(keys);
    args.addAll(Arrays.asList(params));
    return async(readOnlyMode, nodeSource, codec, evalCommandType, args.toArray(), false, noRetry);
}
Also used : RedisException(org.redisson.client.RedisException) RPromise(org.redisson.misc.RPromise) java.util(java.util) NodeType(org.redisson.api.NodeType) Codec(org.redisson.client.codec.Codec) StringCodec(org.redisson.client.codec.StringCodec) ByteBufAllocator(io.netty.buffer.ByteBufAllocator) MessageDigest(java.security.MessageDigest) LoggerFactory(org.slf4j.LoggerFactory) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CompletableFuture(java.util.concurrent.CompletableFuture) RedisClient(org.redisson.client.RedisClient) AtomicReference(java.util.concurrent.atomic.AtomicReference) RFuture(org.redisson.api.RFuture) NodeSource(org.redisson.connection.NodeSource) CompletableFutureWrapper(org.redisson.misc.CompletableFutureWrapper) ByteBuf(io.netty.buffer.ByteBuf) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) BiConsumer(java.util.function.BiConsumer) RedissonReference(org.redisson.RedissonReference) SlotCallback(org.redisson.SlotCallback) Logger(org.slf4j.Logger) LRUCacheMap(org.redisson.cache.LRUCacheMap) ConnectionManager(org.redisson.connection.ConnectionManager) RedissonPromise(org.redisson.misc.RedissonPromise) IOException(java.io.IOException) Collectors(java.util.stream.Collectors) RedisCommands(org.redisson.client.protocol.RedisCommands) ExecutionException(java.util.concurrent.ExecutionException) AtomicLong(java.util.concurrent.atomic.AtomicLong) ByteBufUtil(io.netty.buffer.ByteBufUtil) RedisRedirectException(org.redisson.client.RedisRedirectException) CompletionStage(java.util.concurrent.CompletionStage) ReferenceCountUtil(io.netty.util.ReferenceCountUtil) MasterSlaveEntry(org.redisson.connection.MasterSlaveEntry) Entry(java.util.Map.Entry) RedisCommand(org.redisson.client.protocol.RedisCommand) RedissonObjectBuilder(org.redisson.liveobject.core.RedissonObjectBuilder) RFuture(org.redisson.api.RFuture) NodeSource(org.redisson.connection.NodeSource) CompletableFuture(java.util.concurrent.CompletableFuture) CompletableFutureWrapper(org.redisson.misc.CompletableFutureWrapper) RedisCommand(org.redisson.client.protocol.RedisCommand)

Example 24 with Codec

use of org.redisson.client.codec.Codec in project redisson by redisson.

the class CommandAsyncService method async.

public <V, R> RFuture<R> async(boolean readOnlyMode, NodeSource source, Codec codec, RedisCommand<V> command, Object[] params, boolean ignoreRedirect, boolean noRetry) {
    if (readOnlyMode && command.getName().equals("SORT") && !sortRoSupported.get()) {
        readOnlyMode = false;
    } else if (readOnlyMode && command.getName().equals("SORT") && sortRoSupported.get()) {
        RedisCommand cmd = new RedisCommand("SORT_RO", command.getReplayMultiDecoder());
        CompletableFuture<R> mainPromise = createPromise();
        RedisExecutor<V, R> executor = new RedisExecutor<>(readOnlyMode, source, codec, cmd, params, mainPromise, ignoreRedirect, connectionManager, objectBuilder, referenceType, noRetry);
        executor.execute();
        CompletableFuture<R> result = new CompletableFuture<>();
        mainPromise.whenComplete((r, e) -> {
            if (e != null && e.getMessage().startsWith("ERR unknown command")) {
                sortRoSupported.set(false);
                RFuture<R> future = async(false, source, codec, command, params, ignoreRedirect, noRetry);
                transfer(future.toCompletableFuture(), result);
                return;
            }
            transfer(mainPromise, result);
        });
        return new CompletableFutureWrapper<>(result);
    }
    CompletableFuture<R> mainPromise = createPromise();
    RedisExecutor<V, R> executor = new RedisExecutor<>(readOnlyMode, source, codec, command, params, mainPromise, ignoreRedirect, connectionManager, objectBuilder, referenceType, noRetry);
    executor.execute();
    return new CompletableFutureWrapper<>(mainPromise);
}
Also used : RedisException(org.redisson.client.RedisException) RPromise(org.redisson.misc.RPromise) java.util(java.util) NodeType(org.redisson.api.NodeType) Codec(org.redisson.client.codec.Codec) StringCodec(org.redisson.client.codec.StringCodec) ByteBufAllocator(io.netty.buffer.ByteBufAllocator) MessageDigest(java.security.MessageDigest) LoggerFactory(org.slf4j.LoggerFactory) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CompletableFuture(java.util.concurrent.CompletableFuture) RedisClient(org.redisson.client.RedisClient) AtomicReference(java.util.concurrent.atomic.AtomicReference) RFuture(org.redisson.api.RFuture) NodeSource(org.redisson.connection.NodeSource) CompletableFutureWrapper(org.redisson.misc.CompletableFutureWrapper) ByteBuf(io.netty.buffer.ByteBuf) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) BiConsumer(java.util.function.BiConsumer) RedissonReference(org.redisson.RedissonReference) SlotCallback(org.redisson.SlotCallback) Logger(org.slf4j.Logger) LRUCacheMap(org.redisson.cache.LRUCacheMap) ConnectionManager(org.redisson.connection.ConnectionManager) RedissonPromise(org.redisson.misc.RedissonPromise) IOException(java.io.IOException) Collectors(java.util.stream.Collectors) RedisCommands(org.redisson.client.protocol.RedisCommands) ExecutionException(java.util.concurrent.ExecutionException) AtomicLong(java.util.concurrent.atomic.AtomicLong) ByteBufUtil(io.netty.buffer.ByteBufUtil) RedisRedirectException(org.redisson.client.RedisRedirectException) CompletionStage(java.util.concurrent.CompletionStage) ReferenceCountUtil(io.netty.util.ReferenceCountUtil) MasterSlaveEntry(org.redisson.connection.MasterSlaveEntry) Entry(java.util.Map.Entry) RedisCommand(org.redisson.client.protocol.RedisCommand) RedissonObjectBuilder(org.redisson.liveobject.core.RedissonObjectBuilder) RFuture(org.redisson.api.RFuture) CompletableFuture(java.util.concurrent.CompletableFuture) CompletableFutureWrapper(org.redisson.misc.CompletableFutureWrapper) RedisCommand(org.redisson.client.protocol.RedisCommand)

Example 25 with Codec

use of org.redisson.client.codec.Codec in project redisson by redisson.

the class RedissonCodecTest method testAvro.

@Test
public void testAvro() throws IOException {
    AvroMapper am = new AvroMapper();
    AvroSchema schema = am.schemaFor(TestObject.class);
    Codec avroCodec = new AvroJacksonCodec(TestObject.class, schema);
    Config config = createConfig();
    config.setCodec(avroCodec);
    RedissonClient redisson = Redisson.create(config);
    RBucket<TestObject> b = redisson.getBucket("bucket");
    b.set(new TestObject("1", "2"));
    assertThat(b.get()).isEqualTo(new TestObject("1", "2"));
}
Also used : Codec(org.redisson.client.codec.Codec) AvroSchema(com.fasterxml.jackson.dataformat.avro.AvroSchema) RedissonClient(org.redisson.api.RedissonClient) Config(org.redisson.config.Config) AvroMapper(com.fasterxml.jackson.dataformat.avro.AvroMapper) Test(org.junit.jupiter.api.Test)

Aggregations

Codec (org.redisson.client.codec.Codec)34 PubSubType (org.redisson.client.protocol.pubsub.PubSubType)11 java.util (java.util)10 Collectors (java.util.stream.Collectors)9 ConnectionManager (org.redisson.connection.ConnectionManager)9 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)8 MasterSlaveEntry (org.redisson.connection.MasterSlaveEntry)8 Logger (org.slf4j.Logger)8 LoggerFactory (org.slf4j.LoggerFactory)8 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)7 ChannelFuture (io.netty.channel.ChannelFuture)6 ChannelFutureListener (io.netty.channel.ChannelFutureListener)6 Timeout (io.netty.util.Timeout)6 StringCodec (org.redisson.client.codec.StringCodec)6 ByteBuf (io.netty.buffer.ByteBuf)5 java.util.concurrent (java.util.concurrent)5 CompletableFuture (java.util.concurrent.CompletableFuture)5 PubSubPatternStatusListener (org.redisson.PubSubPatternStatusListener)5 org.redisson.client (org.redisson.client)5 PubSubStatusMessage (org.redisson.client.protocol.pubsub.PubSubStatusMessage)5