org.redisson.client.RedisConnection Java Examples

The following examples show how to use org.redisson.client.RedisConnection. 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: RedisClientTest.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Test
public void testPipelineBigResponse() throws InterruptedException, ExecutionException {
    RedisConnection conn = redisClient.connect();

    List<CommandData<?, ?>> commands = new ArrayList<CommandData<?, ?>>();
    for (int i = 0; i < 1000; i++) {
        CommandData<String, String> cmd1 = conn.create(null, RedisCommands.PING);
        commands.add(cmd1);
    }

    RPromise<Void> p = new RedissonPromise<Void>();
    conn.send(new CommandsData(p, commands, false, false));

    for (CommandData<?, ?> commandData : commands) {
        commandData.getPromise().get();
    }

    conn.sync(RedisCommands.FLUSHDB);
}
 
Example #2
Source File: RedisQueuedBatchExecutor.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Override
protected void handleSuccess(RPromise<R> promise, RFuture<RedisConnection> connectionFuture, R res)
        throws ReflectiveOperationException {
    if (RedisCommands.EXEC.getName().equals(command.getName())) {
        super.handleSuccess(promise, connectionFuture, res);
        return;
    }
    if (RedisCommands.DISCARD.getName().equals(command.getName())) {
        super.handleSuccess(promise, connectionFuture, null);
        if (executed.compareAndSet(false, true)) {
            connectionFuture.getNow().forceFastReconnectAsync().onComplete((r, e) -> {
                releaseConnection(promise, connectionFuture);
            });
        }
        return;
    }
    
    BatchPromise<R> batchPromise = (BatchPromise<R>) promise;
    RPromise<R> sentPromise = (RPromise<R>) batchPromise.getSentPromise();
    super.handleSuccess(sentPromise, connectionFuture, null);
    semaphore.release();
}
 
Example #3
Source File: RedisQueuedBatchExecutor.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Override
protected void handleError(RFuture<RedisConnection> connectionFuture, Throwable cause) {
    if (mainPromise instanceof BatchPromise) {
        BatchPromise<R> batchPromise = (BatchPromise<R>) mainPromise;
        RPromise<R> sentPromise = (RPromise<R>) batchPromise.getSentPromise();
        sentPromise.tryFailure(cause);
        mainPromise.tryFailure(cause);
        if (executed.compareAndSet(false, true)) {
            connectionFuture.getNow().forceFastReconnectAsync().onComplete((res, e) -> {
                RedisQueuedBatchExecutor.super.releaseConnection(mainPromise, connectionFuture);
            });
        }
        semaphore.release();
        return;
    }

    super.handleError(connectionFuture, cause);
}
 
Example #4
Source File: RedisClientTest.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Test
public void test() throws InterruptedException {
    final RedisConnection conn = redisClient.connect();

    conn.sync(StringCodec.INSTANCE, RedisCommands.SET, "test", 0);
    ExecutorService pool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 2);
    for (int i = 0; i < 100000; i++) {
        pool.execute(() -> {
            conn.async(StringCodec.INSTANCE, RedisCommands.INCR, "test");
        });
    }

    pool.shutdown();

    assertThat(pool.awaitTermination(1, TimeUnit.HOURS)).isTrue();

    assertThat((Long) conn.sync(LongCodec.INSTANCE, RedisCommands.GET, "test")).isEqualTo(100000);

    conn.sync(RedisCommands.FLUSHDB);
}
 
Example #5
Source File: ClientConnectionsEntry.java    From redisson with Apache License 2.0 6 votes vote down vote up
private void onConnect(final RedisConnection conn) {
    conn.setConnectedListener(new Runnable() {
        @Override
        public void run() {
            if (!connectionManager.isShuttingDown()) {
                connectionManager.getConnectionEventsHub().fireConnect(conn.getRedisClient().getAddr());
            }
        }
    });
    conn.setDisconnectedListener(new Runnable() {
        @Override
        public void run() {
            if (!connectionManager.isShuttingDown()) {
                connectionManager.getConnectionEventsHub().fireDisconnect(conn.getRedisClient().getAddr());
            }
        }
    });
    
    connectionManager.getConnectionEventsHub().fireConnect(conn.getRedisClient().getAddr());
}
 
Example #6
Source File: RedisConnectionInstrumentation.java    From apm-agent-java with Apache License 2.0 6 votes vote down vote up
@Advice.OnMethodEnter
private static void beforeSend(@Advice.This RedisConnection connection,
                               @Advice.Argument(0) Object args,
                               @Nullable @Advice.Local("span") Span span) {
    span = RedisSpanUtils.createRedisSpan("");
    if (span != null) {
        // get command
        if (args instanceof CommandsData) {
            List<CommandData<?, ?>> commands = ((CommandsData) args).getCommands();
            if (commands != null && !commands.isEmpty()) {
                span.appendToName(commands.get(0).getCommand().getName()).appendToName("... [bulk]");
            }
        } else if (args instanceof CommandData) {
            span.appendToName(((CommandData) args).getCommand().getName());
        }

        // get connection address
        Channel channel = connection.getChannel();
        InetSocketAddress remoteAddress = (InetSocketAddress) channel.remoteAddress();
        span.getContext().getDestination()
            .withAddress(remoteAddress.getAddress().getHostAddress())
            .withPort(remoteAddress.getPort());
    }
}
 
Example #7
Source File: MasterSlaveConnectionManager.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Override
public RFuture<RedisConnection> connectionReadOp(NodeSource source, RedisCommand<?> command) {
    MasterSlaveEntry entry = getEntry(source);
    if (entry == null) {
        return createNodeNotFoundFuture(source);
    }

    if (source.getRedirect() != null) {
        return entry.connectionReadOp(command, source.getAddr());
    }
    if (source.getRedisClient() != null) {
        return entry.connectionReadOp(command, source.getRedisClient());
    }
    
    return entry.connectionReadOp(command);
}
 
Example #8
Source File: RedisClientTest.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Test
public void testPipeline() throws InterruptedException, ExecutionException {
    RedisConnection conn = redisClient.connect();

    conn.sync(StringCodec.INSTANCE, RedisCommands.SET, "test", 0);

    List<CommandData<?, ?>> commands = new ArrayList<CommandData<?, ?>>();
    CommandData<String, String> cmd1 = conn.create(null, RedisCommands.PING);
    commands.add(cmd1);
    CommandData<Long, Long> cmd2 = conn.create(null, RedisCommands.INCR, "test");
    commands.add(cmd2);
    CommandData<Long, Long> cmd3 = conn.create(null, RedisCommands.INCR, "test");
    commands.add(cmd3);
    CommandData<String, String> cmd4 = conn.create(null, RedisCommands.PING);
    commands.add(cmd4);

    RPromise<Void> p = new RedissonPromise<Void>();
    conn.send(new CommandsData(p, commands, false, false));

    assertThat(cmd1.getPromise().get()).isEqualTo("PONG");
    assertThat(cmd2.getPromise().get()).isEqualTo(1);
    assertThat(cmd3.getPromise().get()).isEqualTo(2);
    assertThat(cmd4.getPromise().get()).isEqualTo("PONG");

    conn.sync(RedisCommands.FLUSHDB);
}
 
Example #9
Source File: SpringNamespaceWikiTest.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Test
public void testRedisClient() throws Exception {
    RedisRunner.RedisProcess run = new RedisRunner()
            .requirepass("do_not_use_if_it_is_not_set")
            .nosave()
            .randomDir()
            .run();
    try {
        ClassPathXmlApplicationContext context
                = new ClassPathXmlApplicationContext("classpath:org/redisson/spring/support/namespace_wiki_redis_client.xml");
        RedisClient redisClient = context.getBean(RedisClient.class);
        RedisConnection connection = redisClient.connect();
        Map<String, String> info = connection.sync(RedisCommands.INFO_ALL);
        assertThat(info, notNullValue());
        assertThat(info, not(info.isEmpty()));
        ((ConfigurableApplicationContext) context).close();
    } finally {
        run.stop();
    }
}
 
Example #10
Source File: RedisRunner.java    From redisson with Apache License 2.0 5 votes vote down vote up
public int stop() {
    if (runner.isNosave() && !runner.isRandomDir()) {
        RedisClient c = createDefaultRedisClientInstance();
        RedisConnection connection = c.connect();
        try {
            connection.async(new RedisStrictCommand<Void>("SHUTDOWN", "NOSAVE", new VoidReplayConvertor()))
                    .await(3, TimeUnit.SECONDS);
        } catch (InterruptedException interruptedException) {
            //shutdown via command failed, lets wait and kill it later.
        }
        c.shutdown();
        connection.closeAsync().syncUninterruptibly();
    }
    Process p = redisProcess;
    p.destroy();
    boolean normalTermination = false;
    try {
        normalTermination = p.waitFor(5, TimeUnit.SECONDS);
    } catch (InterruptedException ex) {
        //OK lets hurry up by force kill;
    }
    if (!normalTermination) {
        p = p.destroyForcibly();
    }
    cleanup();
    int exitCode = p.exitValue();
    return exitCode == 1 && RedissonRuntimeEnvironment.isWindows ? 0 : exitCode;
}
 
Example #11
Source File: RedisRunner.java    From redisson with Apache License 2.0 5 votes vote down vote up
public RedisVersion getRedisVersion() {
    if (redisVersion == null) {
        RedisConnection c = createRedisClientInstance().connect();
        Map<String, String> serverMap = c.sync(RedisCommands.INFO_SERVER);
        redisVersion = new RedisVersion(serverMap.get("redis_version"));
        c.closeAsync();
    }
    return redisVersion;
}
 
Example #12
Source File: RedisRunner.java    From redisson with Apache License 2.0 5 votes vote down vote up
public void restart(int startTimeout) {
    if (runner.isNosave() && !runner.isRandomDir()) {
        RedisClient c = createDefaultRedisClientInstance();
        RedisConnection connection = c.connect();
        try {
            connection.async(new RedisStrictCommand<Void>("SHUTDOWN", "NOSAVE", new VoidReplayConvertor()))
                    .await(3, TimeUnit.SECONDS);
        } catch (InterruptedException interruptedException) {
            //shutdown via command failed, lets wait and kill it later.
        }
        c.shutdown();
        connection.closeAsync().syncUninterruptibly();
    }
    Process p = redisProcess;
    p.destroy();
    boolean normalTermination = false;
    try {
        normalTermination = p.waitFor(5, TimeUnit.SECONDS);
    } catch (InterruptedException ex) {
        //OK lets hurry up by force kill;
    }
    if (!normalTermination) {
        p = p.destroyForcibly();
    }
    
    Executors.newScheduledThreadPool(1).schedule(() -> {
        try {
            redisProcess = runner.run().redisProcess;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }, startTimeout, TimeUnit.SECONDS);
}
 
Example #13
Source File: RedisRunner.java    From redisson with Apache License 2.0 5 votes vote down vote up
public RedisVersion getRedisVersion() {
    if (redisVersion == null) {
        RedisConnection c = createRedisClientInstance().connect();
        Map<String, String> serverMap = c.sync(RedisCommands.INFO_SERVER);
        redisVersion = new RedisVersion(serverMap.get("redis_version"));
        c.closeAsync();
    }
    return redisVersion;
}
 
Example #14
Source File: RedisRunner.java    From redisson with Apache License 2.0 5 votes vote down vote up
public int stop() {
    if (runner.isNosave() && !runner.isRandomDir()) {
        RedisClient c = createDefaultRedisClientInstance();
        RedisConnection connection = c.connect();
        try {
            connection.async(new RedisStrictCommand<Void>("SHUTDOWN", "NOSAVE", new VoidReplayConvertor()))
                    .await(3, TimeUnit.SECONDS);
        } catch (InterruptedException interruptedException) {
            //shutdown via command failed, lets wait and kill it later.
        }
        c.shutdown();
        connection.closeAsync().syncUninterruptibly();
    }
    Process p = redisProcess;
    p.destroy();
    boolean normalTermination = false;
    try {
        normalTermination = p.waitFor(5, TimeUnit.SECONDS);
    } catch (InterruptedException ex) {
        //OK lets hurry up by force kill;
    }
    if (!normalTermination) {
        p = p.destroyForcibly();
    }
    cleanup();
    int exitCode = p.exitValue();
    return exitCode == 1 && RedissonRuntimeEnvironment.isWindows ? 0 : exitCode;
}
 
Example #15
Source File: RedisClientTest.java    From redisson with Apache License 2.0 5 votes vote down vote up
@Test
public void testBigRequest() throws InterruptedException, ExecutionException {
    RedisConnection conn = redisClient.connect();

    for (int i = 0; i < 50; i++) {
        conn.sync(StringCodec.INSTANCE, RedisCommands.HSET, "testmap", i, "2");
    }

    Map<Object, Object> res = conn.sync(StringCodec.INSTANCE, RedisCommands.HGETALL, "testmap");
    assertThat(res.size()).isEqualTo(50);

    conn.sync(RedisCommands.FLUSHDB);
}
 
Example #16
Source File: ConnectionWatchdog.java    From redisson with Apache License 2.0 5 votes vote down vote up
private void refresh(RedisConnection connection, Channel channel) {
    CommandData<?, ?> currentCommand = connection.getCurrentCommand();
    connection.fireConnected();
    connection.updateChannel(channel);
    
    if (connection.isFastReconnect()) {
        connection.clearFastReconnect();
    }

    reattachBlockingQueue(connection, currentCommand);            
    reattachPubSub(connection);
}
 
Example #17
Source File: PingConnectionHandler.java    From redisson with Apache License 2.0 5 votes vote down vote up
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    RedisConnection connection = RedisConnection.getFrom(ctx.channel());
    connection.getConnectionPromise().onComplete((res, e) -> {
        if (e == null) {
            sendPing(ctx);
        }
    });
    ctx.fireChannelActive();
}
 
Example #18
Source File: RedisQueuedBatchExecutor.java    From redisson with Apache License 2.0 5 votes vote down vote up
@Override
protected RFuture<RedisConnection> getConnection() {
    MasterSlaveEntry msEntry = getEntry(source);
    ConnectionEntry entry = connections.get(msEntry);
    if (entry == null) {
        entry = new ConnectionEntry();
        ConnectionEntry oldEntry = connections.putIfAbsent(msEntry, entry);
        if (oldEntry != null) {
            entry = oldEntry;
        }
    }

    
    if (entry.getConnectionFuture() != null) {
        return entry.getConnectionFuture();
    }
    
    synchronized (this) {
        if (entry.getConnectionFuture() != null) {
            return entry.getConnectionFuture();
        }
    
        RFuture<RedisConnection> connectionFuture;
        if (this.options.getExecutionMode() == ExecutionMode.REDIS_WRITE_ATOMIC) {
            connectionFuture = connectionManager.connectionWriteOp(source, null);
        } else {
            connectionFuture = connectionManager.connectionReadOp(source, null);
        }
        connectionFuture.syncUninterruptibly();
        entry.setConnectionFuture(connectionFuture);
        return connectionFuture;
    }
}
 
Example #19
Source File: RedisRunner.java    From redisson with Apache License 2.0 5 votes vote down vote up
public RedisVersion getRedisVersion() {
    if (redisVersion == null) {
        RedisConnection c = createRedisClientInstance().connect();
        Map<String, String> serverMap = c.sync(RedisCommands.INFO_SERVER);
        redisVersion = new RedisVersion(serverMap.get("redis_version"));
        c.closeAsync();
    }
    return redisVersion;
}
 
Example #20
Source File: LoadBalancerManager.java    From redisson with Apache License 2.0 5 votes vote down vote up
public RFuture<RedisConnection> getConnection(RedisCommand<?> command, RedisURI addr) {
    ClientConnectionsEntry entry = getEntry(addr);
    if (entry != null) {
        return slaveConnectionPool.get(command, entry);
    }
    RedisConnectionException exception = new RedisConnectionException("Can't find entry for " + addr);
    return RedissonPromise.newFailedFuture(exception);
}
 
Example #21
Source File: LoadBalancerManager.java    From redisson with Apache License 2.0 5 votes vote down vote up
public RFuture<RedisConnection> getConnection(RedisCommand<?> command, RedisClient client) {
    ClientConnectionsEntry entry = getEntry(client);
    if (entry != null) {
        return slaveConnectionPool.get(command, entry);
    }
    RedisConnectionException exception = new RedisConnectionException("Can't find entry for " + client);
    return RedissonPromise.newFailedFuture(exception);
}
 
Example #22
Source File: MasterSlaveConnectionManager.java    From redisson with Apache License 2.0 5 votes vote down vote up
@Override
public void releaseRead(NodeSource source, RedisConnection connection) {
    MasterSlaveEntry entry = getEntry(source);
    if (entry == null) {
        log.error("Node: " + source + " can't be found");
    } else {
        entry.releaseRead(connection);
    }
    
}
 
Example #23
Source File: MasterSlaveConnectionManager.java    From redisson with Apache License 2.0 5 votes vote down vote up
@Override
public void releaseWrite(NodeSource source, RedisConnection connection) {
    MasterSlaveEntry entry = getEntry(source);
    if (entry == null) {
        log.error("Node: " + source + " can't be found");
    } else {
        entry.releaseWrite(connection);
    }
}
 
Example #24
Source File: ClientConnectionsEntry.java    From redisson with Apache License 2.0 5 votes vote down vote up
public void releaseConnection(RedisConnection connection) {
    if (client != connection.getRedisClient()) {
        connection.closeAsync();
        return;
    }

    connection.setLastUsageTime(System.currentTimeMillis());
    freeConnections.add(connection);
}
 
Example #25
Source File: ClientConnectionsEntry.java    From redisson with Apache License 2.0 5 votes vote down vote up
public RFuture<RedisConnection> connect() {
    RFuture<RedisConnection> future = client.connectAsync();
    future.onComplete((conn, e) -> {
        if (e != null) {
            return;
        }
        
        onConnect(conn);
        log.debug("new connection created: {}", conn);
        
        allConnections.add(conn);
    });
    return future;
}
 
Example #26
Source File: MasterSlaveConnectionManager.java    From redisson with Apache License 2.0 5 votes vote down vote up
protected RFuture<RedisConnection> createNodeNotFoundFuture(NodeSource source) {
    RedisNodeNotFoundException ex;
    if (source.getSlot() != null && source.getAddr() == null && source.getRedisClient() == null) {
        ex = new RedisNodeNotFoundException("Node for slot: " + source.getSlot() + " hasn't been discovered yet. Check cluster slots coverage using CLUSTER NODES command. Increase value of retryAttempts and/or retryInterval settings.");
    } else {
        ex = new RedisNodeNotFoundException("Node: " + source + " hasn't been discovered yet. Increase value of retryAttempts and/or retryInterval settings.");
    }
    return RedissonPromise.newFailedFuture(ex);
}
 
Example #27
Source File: MasterSlaveConnectionManager.java    From redisson with Apache License 2.0 5 votes vote down vote up
@Override
public RFuture<RedisConnection> connectionWriteOp(NodeSource source, RedisCommand<?> command) {
    MasterSlaveEntry entry = getEntry(source);
    if (entry == null) {
        return createNodeNotFoundFuture(source);
    }
    // fix for https://github.com/redisson/redisson/issues/1548
    if (source.getRedirect() != null 
            && !RedisURI.compare(entry.getClient().getAddr(), source.getAddr()) 
                && entry.hasSlave(source.getAddr())) {
        return entry.redirectedConnectionWriteOp(command, source.getAddr());
    }
    return entry.connectionWriteOp(command);
}
 
Example #28
Source File: MasterSlaveConnectionManager.java    From redisson with Apache License 2.0 5 votes vote down vote up
protected final RFuture<RedisConnection> connectToNode(BaseMasterSlaveServersConfig<?> cfg, RedisURI addr, RedisClient client, String sslHostname) {
    final Object key;
    if (client != null) {
        key = client;
    } else {
        key = addr;
    }
    RedisConnection conn = nodeConnections.get(key);
    if (conn != null) {
        if (!conn.isActive()) {
            nodeConnections.remove(key);
            conn.closeAsync();
        } else {
            return RedissonPromise.newSucceededFuture(conn);
        }
    }

    if (addr != null) {
        client = createClient(NodeType.MASTER, addr, cfg.getConnectTimeout(), cfg.getTimeout(), sslHostname);
    }
    final RPromise<RedisConnection> result = new RedissonPromise<RedisConnection>();
    RFuture<RedisConnection> future = client.connectAsync();
    future.onComplete((connection, e) -> {
        if (e != null) {
            result.tryFailure(e);
            return;
        }

        if (connection.isActive()) {
            nodeConnections.put(key, connection);
            result.trySuccess(connection);
        } else {
            connection.closeAsync();
            result.tryFailure(new RedisException("Connection to " + connection.getRedisClient().getAddr() + " is not active!"));
        }
    });

    return result;
}
 
Example #29
Source File: MasterSlaveEntry.java    From redisson with Apache License 2.0 5 votes vote down vote up
public void releaseRead(RedisConnection connection) {
    if (config.getReadMode() == ReadMode.MASTER) {
        releaseWrite(connection);
        return;
    }
    slaveBalancer.returnConnection(connection);
}
 
Example #30
Source File: IdleConnectionWatcher.java    From redisson with Apache License 2.0 5 votes vote down vote up
public Entry(int minimumAmount, int maximumAmount, Collection<? extends RedisConnection> connections,
             AsyncSemaphore freeConnectionsCounter, Function<RedisConnection, Boolean> deleteHandler) {
    super();
    this.minimumAmount = minimumAmount;
    this.maximumAmount = maximumAmount;
    this.connections = connections;
    this.freeConnectionsCounter = freeConnectionsCounter;
    this.deleteHandler = deleteHandler;
}