io.lettuce.core.api.StatefulRedisConnection Java Examples

The following examples show how to use io.lettuce.core.api.StatefulRedisConnection. 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: RedisQueue.java    From NetDiscovery with Apache License 2.0 7 votes vote down vote up
@Override
protected void pushWhenNoDuplicate(Request request) {
    StatefulRedisConnection<String, String> connection = redisClient.connect();
    RedisCommands<String, String> commands = connection.sync();
    try {
        commands.lpush(request.getSpiderName(), request.getUrl());

        if (hasExtraRequestInfo(request)) {
            String field = DigestUtils.sha1Hex(request.getUrl());
            String value = SerializableUtils.toJson(request);
            commands.hset((ITEM_PREFIX + request.getUrl()), field, value);
        }

    } finally {
        connection.close();
    }

}
 
Example #2
Source File: RedisQueue.java    From NetDiscovery with Apache License 2.0 6 votes vote down vote up
@Override
public boolean isDuplicate(Request request) {
    StatefulRedisConnection<String, String> connection = redisClient.connect();
    RedisCommands<String, String> commands = connection.sync();

    try {
        if (request.isCheckDuplicate()) {
            return commands.sadd(getSetKey(request), request.getUrl()) == 0;
        } else {
            commands.sadd(getSetKey(request), request.getUrl());
            return false;
        }
    } finally {
        connection.close();
    }
}
 
Example #3
Source File: TracingLettuce52Test.java    From java-redis-client with Apache License 2.0 6 votes vote down vote up
@Test
public void sync() {
  RedisClient client = RedisClient.create("redis://localhost");

  StatefulRedisConnection<String, String> connection =
      new TracingStatefulRedisConnection<>(client.connect(),
          new TracingConfiguration.Builder(mockTracer).build());
  RedisCommands<String, String> commands = connection.sync();

  assertEquals("OK", commands.set("key", "value"));
  assertEquals("value", commands.get("key"));

  connection.close();

  client.shutdown();

  List<MockSpan> spans = mockTracer.finishedSpans();
  assertEquals(2, spans.size());
}
 
Example #4
Source File: LettuceConnectionManager.java    From jetcache with Apache License 2.0 6 votes vote down vote up
public Object reactiveCommands(AbstractRedisClient redisClient) {
    connection(redisClient);
    LettuceObjects lo = getLettuceObjectsFromMap(redisClient);
    if (lo.reactiveCommands == null) {
        if (lo.connection instanceof StatefulRedisConnection) {
            lo.reactiveCommands = ((StatefulRedisConnection) lo.connection).reactive();
        } else if (lo.connection instanceof StatefulRedisClusterConnection) {
            lo.reactiveCommands = ((StatefulRedisClusterConnection) lo.connection).reactive();
        } else if (lo.connection instanceof StatefulRedisSentinelConnection) {
            lo.reactiveCommands = ((StatefulRedisSentinelConnection) lo.connection).reactive();
        } else {
            throw new CacheConfigException("type " + lo.connection.getClass() + " is not supported");
        }
    }
    return lo.reactiveCommands;
}
 
Example #5
Source File: TracingLettuce50Test.java    From java-redis-client with Apache License 2.0 6 votes vote down vote up
@Test
public void sync() {
  RedisClient client = RedisClient.create("redis://localhost");

  StatefulRedisConnection<String, String> connection =
      new TracingStatefulRedisConnection<>(client.connect(),
          new TracingConfiguration.Builder(mockTracer).build());
  RedisCommands<String, String> commands = connection.sync();

  assertEquals("OK", commands.set("key", "value"));
  assertEquals("value", commands.get("key"));

  connection.close();

  client.shutdown();

  List<MockSpan> spans = mockTracer.finishedSpans();
  assertEquals(2, spans.size());
}
 
Example #6
Source File: LettuceConnectionManager.java    From jetcache with Apache License 2.0 6 votes vote down vote up
public Object asyncCommands(AbstractRedisClient redisClient) {
    connection(redisClient);
    LettuceObjects lo = getLettuceObjectsFromMap(redisClient);
    if (lo.asyncCommands == null) {
        if (lo.connection instanceof StatefulRedisConnection) {
            lo.asyncCommands = ((StatefulRedisConnection) lo.connection).async();
        } else if (lo.connection instanceof StatefulRedisClusterConnection) {
            lo.asyncCommands = ((StatefulRedisClusterConnection) lo.connection).async();
        } else if (lo.connection instanceof StatefulRedisSentinelConnection) {
            lo.asyncCommands = ((StatefulRedisSentinelConnection) lo.connection).async();
        } else {
            throw new CacheConfigException("type " + lo.connection.getClass() + " is not supported");
        }
    }
    return lo.asyncCommands;
}
 
Example #7
Source File: TracingLettuce51Test.java    From java-redis-client with Apache License 2.0 6 votes vote down vote up
@Test
public void sync() {
  RedisClient client = RedisClient.create("redis://localhost");

  StatefulRedisConnection<String, String> connection =
      new TracingStatefulRedisConnection<>(client.connect(),
          new TracingConfiguration.Builder(mockTracer).build());
  RedisCommands<String, String> commands = connection.sync();

  assertEquals("OK", commands.set("key", "value"));
  assertEquals("value", commands.get("key"));

  connection.close();

  client.shutdown();

  List<MockSpan> spans = mockTracer.finishedSpans();
  assertEquals(2, spans.size());
}
 
Example #8
Source File: LettuceConnectionManager.java    From jetcache with Apache License 2.0 6 votes vote down vote up
public Object commands(AbstractRedisClient redisClient) {
    connection(redisClient);
    LettuceObjects lo = getLettuceObjectsFromMap(redisClient);
    if (lo.commands == null) {
        if (lo.connection instanceof StatefulRedisConnection) {
            lo.commands = ((StatefulRedisConnection) lo.connection).sync();
        } else if (lo.connection instanceof StatefulRedisClusterConnection) {
            lo.commands = ((StatefulRedisClusterConnection) lo.connection).sync();
        } else if (lo.connection instanceof StatefulRedisSentinelConnection) {
            lo.commands = ((StatefulRedisSentinelConnection) lo.connection).sync();
        }else {
            throw new CacheConfigException("type " + lo.connection.getClass() + " is not supported");
        }
    }
    return lo.commands;
}
 
Example #9
Source File: LettuceTest.java    From java-specialagent with Apache License 2.0 6 votes vote down vote up
@Test
public void testReactiveMono(MockTracer tracer) {
  try (final StatefulRedisConnection<String,String> connection = client.connect()) {
    final RedisReactiveCommands<String, String> commands = connection.reactive();
    commands.set("key", "value").subscribe(new Consumer<String>() {
      @Override
      public void accept(final String res) {
        assertEquals("OK", res);
      }
    });
    await().atMost(15, TimeUnit.SECONDS).until(TestUtil.reportedSpansSize(tracer), equalTo(2));
  }

  final List<MockSpan> spans = tracer.finishedSpans();
  assertEquals(2, spans.size());
}
 
Example #10
Source File: LettuceSessionClient.java    From redis-session-manager with Apache License 2.0 6 votes vote down vote up
<T> T async(Function<RedisAsyncCommands<String, Object>, T> s) {
    try (StatefulRedisConnection<String, Object> conn = pool.borrowObject()) {
        return s.apply(conn.async());
    } catch (Exception e) {
        log.error("Failed to borrow a connection", e);
        return null;
    }
}
 
Example #11
Source File: LettuceController.java    From skywalking with Apache License 2.0 6 votes vote down vote up
@RequestMapping("/lettuce-case")
@ResponseBody
public String lettuceCase() {
    RedisClient redisClient = RedisClient.create("redis://" + address);
    StatefulRedisConnection<String, String> connection0 = redisClient.connect();
    RedisCommands<String, String> syncCommand = connection0.sync();
    syncCommand.get("key");

    StatefulRedisConnection<String, String> connection1 = redisClient.connect();
    RedisAsyncCommands<String, String> asyncCommands = connection1.async();
    asyncCommands.setAutoFlushCommands(false);
    List<RedisFuture<?>> futures = new ArrayList<>();
    futures.add(asyncCommands.set("key0", "value0"));
    futures.add(asyncCommands.set("key1", "value1"));
    asyncCommands.flushCommands();
    LettuceFutures.awaitAll(5, TimeUnit.SECONDS, futures.toArray(new RedisFuture[futures.size()]));

    connection0.close();
    connection1.close();
    redisClient.shutdown();
    return "Success";
}
 
Example #12
Source File: RedisQueue.java    From NetDiscovery with Apache License 2.0 6 votes vote down vote up
@Override
public synchronized Request poll(String spiderName) {
    StatefulRedisConnection<String, String> connection = redisClient.connect();
    RedisCommands<String, String> commands = connection.sync();
    try {
        String url = commands.lpop(getQueueKey(spiderName));
        if (url == null) {
            return null;
        }

        String key = ITEM_PREFIX + url;
        String field = DigestUtils.sha1Hex(url);
        String result = commands.hget(key, field);

        if (result != null) {

            return SerializableUtils.fromJson(result, Request.class);
        }

        return new Request(url);
    } finally {
        connection.close();
    }
}
 
Example #13
Source File: RedisPriorityQueue.java    From NetDiscovery with Apache License 2.0 6 votes vote down vote up
@Override
protected void pushWhenNoDuplicate(Request request) {

    StatefulRedisConnection<String, String> connection = redisClient.connect();
    RedisCommands<String, String> commands = connection.sync();

    try {
        if (request.getPriority() > 0) {
            commands.zadd(getZsetPriorityKey(request.getSpiderName()), request.getPriority(), request.getUrl());
        } else {
            commands.lpush(getQueueNormalKey(request.getSpiderName()), request.getUrl());
        }

        setExtrasInItem(commands, request);
    } finally {
        connection.close();
    }
}
 
Example #14
Source File: TracingLettuce52Test.java    From java-redis-client with Apache License 2.0 5 votes vote down vote up
@Test
public void async_continue_span() throws Exception {
  final MockSpan parent = mockTracer.buildSpan("test").start();
  try (Scope ignored = mockTracer.activateSpan(parent)) {
    Span activeSpan = mockTracer.activeSpan();

    RedisClient client = RedisClient.create("redis://localhost");

    StatefulRedisConnection<String, String> connection =
        new TracingStatefulRedisConnection<>(client.connect(),
            new TracingConfiguration.Builder(mockTracer).build());

    RedisAsyncCommands<String, String> commands = connection.async();

    assertEquals("OK",
        commands.set("key2", "value2").toCompletableFuture().thenApply(s -> {
          assertSame(activeSpan, mockTracer.activeSpan());
          return s;
        }).get(15, TimeUnit.SECONDS));

    connection.close();

    client.shutdown();
  }
  parent.finish();
  List<MockSpan> spans = mockTracer.finishedSpans();
  assertEquals(2, spans.size());
}
 
Example #15
Source File: ProtobufRedisLoadingCache.java    From curiostack with MIT License 5 votes vote down vote up
private <K extends Message, V extends Message> RemoteCache<K, V> createRedisRemoteCache(
    String name, RedisClient redisClient, K keyPrototype, V valuePrototype) {
  StatefulRedisConnection<K, V> connection =
      redisClient.connect(
          new ProtobufRedisCodec<>(
              (name + ":").getBytes(StandardCharsets.UTF_8), keyPrototype, valuePrototype));
  return new RedisRemoteCache<>(connection.async(), name, meterRegistry);
}
 
Example #16
Source File: RedisPriorityQueue.java    From NetDiscovery with Apache License 2.0 5 votes vote down vote up
@Override
public synchronized Request poll(String spiderName) {
    StatefulRedisConnection<String, String> connection = redisClient.connect();
    RedisCommands<String, String> commands = connection.sync();
    try {
        String url = getRequest(commands, spiderName);
        if (Preconditions.isBlank(url)) {
            return null;
        }

        return getExtrasInItem(commands, url, spiderName);
    } finally {
        connection.close();
    }
}
 
Example #17
Source File: RedisLettuceCacheFailTest.java    From jetcache with Apache License 2.0 5 votes vote down vote up
@BeforeEach
public void setup() {
    client = mock(RedisClient.class);
    StatefulRedisConnection connection = mock(StatefulRedisConnection.class);
    asyncCommands = mock(RedisAsyncCommands.class);
    when(client.connect((JetCacheCodec) any())).thenReturn(connection);
    when(connection.sync()).thenReturn(null);
    when(connection.async()).thenReturn(asyncCommands);

    cache = RedisLettuceCacheBuilder.createRedisLettuceCacheBuilder()
            .redisClient(client)
            .keyPrefix("fail_test")
            .buildCache();
}
 
Example #18
Source File: LettuceTest.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
@Test
public void testAsync(final MockTracer tracer) throws Exception {
  try (final StatefulRedisConnection<String,String> connection = client.connect()) {
    final RedisAsyncCommands<String,String> commands = connection.async();
    assertEquals("OK", commands.set("key2", "value2").get(15, TimeUnit.SECONDS));
    assertEquals("value2", commands.get("key2").get(15, TimeUnit.SECONDS));
  }

  final List<MockSpan> spans = tracer.finishedSpans();
  assertEquals(3, spans.size());
}
 
Example #19
Source File: RedisLettuceStarterTest.java    From jetcache with Apache License 2.0 5 votes vote down vote up
@Test
public void tests() throws Exception {
    if (RedisLettuceCacheTest.checkOS()) {
        System.setProperty("spring.profiles.active", "redislettuce-cluster");
    } else {
        System.setProperty("spring.profiles.active", "redislettuce");
    }
    context = SpringApplication.run(RedisLettuceStarterTest.class);
    doTest();
    A bean = context.getBean(A.class);
    bean.test();

    RedisClient t1 = (RedisClient) context.getBean("defaultClient");
    RedisClient t2 = (RedisClient) context.getBean("a1Client");
    Assert.assertNotNull(t1);
    Assert.assertNotNull(t2);
    Assert.assertNotSame(t1, t2);

    AutoConfigureBeans acb = context.getBean(AutoConfigureBeans.class);

    String key = "remote.A1";
    Assert.assertTrue(new LettuceFactory(acb, key, StatefulRedisConnection.class).getObject() instanceof StatefulRedisConnection);
    Assert.assertTrue(new LettuceFactory(acb, key, RedisCommands.class).getObject() instanceof RedisCommands);
    Assert.assertTrue(new LettuceFactory(acb, key, RedisAsyncCommands.class).getObject() instanceof RedisAsyncCommands);
    Assert.assertTrue(new LettuceFactory(acb, key, RedisReactiveCommands.class).getObject() instanceof RedisReactiveCommands);

    if (RedisLettuceCacheTest.checkOS()) {
        key = "remote.A2";
        Assert.assertTrue(new LettuceFactory(acb, key, RedisClusterClient.class).getObject() instanceof RedisClusterClient);
        Assert.assertTrue(new LettuceFactory(acb, key, RedisClusterCommands.class).getObject() instanceof RedisClusterCommands);
        Assert.assertTrue(new LettuceFactory(acb, key, RedisClusterAsyncCommands.class).getObject() instanceof RedisClusterAsyncCommands);
        Assert.assertTrue(new LettuceFactory(acb, key, RedisClusterReactiveCommands.class).getObject() instanceof RedisClusterReactiveCommands);

        key = "remote.A2_slave";
        Assert.assertTrue(new LettuceFactory(acb, key, RedisClusterClient.class).getObject() instanceof RedisClusterClient);
    }
}
 
Example #20
Source File: LettuceDriver.java    From redis-scheduler with MIT License 5 votes vote down vote up
@Override
public <T> T fetch(Function<Commands, T> block) {
    try (StatefulRedisConnection<String, String> connection = client.connect()) {
        RedisCommands<String, String> commands = connection.sync();
        return block.apply(new LettuceCommands(commands));
    } catch (RedisConnectionException e) {
        throw new RedisConnectException(e);
    }
}
 
Example #21
Source File: RedisKeyValueStoreTest.java    From incubator-tuweni with Apache License 2.0 5 votes vote down vote up
@Test
void testPutAndGet(@RedisPort Integer redisPort) throws Exception {
  KeyValueStore<Bytes, Bytes> store = RedisKeyValueStore
      .open(redisPort, Function.identity(), Function.identity(), Function.identity(), Function.identity());
  AsyncCompletion completion = store.putAsync(Bytes.of(123), Bytes.of(10, 12, 13));
  completion.join();
  Bytes value = store.getAsync(Bytes.of(123)).get();
  assertNotNull(value);
  assertEquals(Bytes.of(10, 12, 13), value);
  RedisClient client =
      RedisClient.create(RedisURI.create(InetAddress.getLoopbackAddress().getHostAddress(), redisPort));
  try (StatefulRedisConnection<Bytes, Bytes> conn = client.connect(new RedisBytesCodec())) {
    assertEquals(Bytes.of(10, 12, 13), conn.sync().get(Bytes.of(123)));
  }
}
 
Example #22
Source File: TracingLettuce50Test.java    From java-redis-client with Apache License 2.0 5 votes vote down vote up
@Test
public void async_continue_span() throws Exception {
  final MockSpan parent = mockTracer.buildSpan("test").start();
  try (Scope ignored = mockTracer.activateSpan(parent)) {
    Span activeSpan = mockTracer.activeSpan();

    RedisClient client = RedisClient.create("redis://localhost");

    StatefulRedisConnection<String, String> connection =
        new TracingStatefulRedisConnection<>(client.connect(),
            new TracingConfiguration.Builder(mockTracer).build());

    RedisAsyncCommands<String, String> commands = connection.async();

    assertEquals("OK",
        commands.set("key2", "value2").toCompletableFuture().thenApply(s -> {
          assertSame(activeSpan, mockTracer.activeSpan());
          return s;
        }).get(15, TimeUnit.SECONDS));

    connection.close();

    client.shutdown();
  }
  parent.finish();
  List<MockSpan> spans = mockTracer.finishedSpans();
  assertEquals(2, spans.size());
}
 
Example #23
Source File: TracingLettuce51Test.java    From java-redis-client with Apache License 2.0 5 votes vote down vote up
@Test
public void async_continue_span() throws Exception {
  final MockSpan parent = mockTracer.buildSpan("test").start();
  try (Scope ignored = mockTracer.activateSpan(parent)) {
    Span activeSpan = mockTracer.activeSpan();

    RedisClient client = RedisClient.create("redis://localhost");

    StatefulRedisConnection<String, String> connection =
        new TracingStatefulRedisConnection<>(client.connect(),
            new TracingConfiguration.Builder(mockTracer).build());

    RedisAsyncCommands<String, String> commands = connection.async();

    assertEquals("OK",
        commands.set("key2", "value2").toCompletableFuture().thenApply(s -> {
          assertSame(activeSpan, mockTracer.activeSpan());
          return s;
        }).get(15, TimeUnit.SECONDS));

    connection.close();

    client.shutdown();
  }
  parent.finish();
  List<MockSpan> spans = mockTracer.finishedSpans();
  assertEquals(2, spans.size());
}
 
Example #24
Source File: RedisRateLimiterFactory.java    From ratelimitj with Apache License 2.0 5 votes vote down vote up
private StatefulRedisConnection<String, String> getConnection() {
    // going to ignore race conditions at the cost of having multiple connections
    if (connection == null) {
        connection = client.connect();
    }
    return connection;
}
 
Example #25
Source File: LettuceSessionClient.java    From redis-session-manager with Apache License 2.0 5 votes vote down vote up
<T> T sync(Function<RedisCommands<String, Object>, T> s) {
    try (StatefulRedisConnection<String, Object> conn = pool.borrowObject()) {
        return s.apply(conn.sync());
    } catch (Exception e) {
        log.error("Failed to borrow a connection", e);
        return null;
    }
}
 
Example #26
Source File: LettuceSessionManager.java    From redis-session-manager with Apache License 2.0 5 votes vote down vote up
private GenericObjectPool<StatefulRedisConnection<String, Object>> createPool(List<String> nodes, RedisCodec<String, Object> codec) {
    GenericObjectPoolConfig<StatefulRedisConnection<String, Object>> cfg = new GenericObjectPoolConfig<>();
    cfg.setTestOnBorrow(true);
    cfg.setMinEvictableIdleTimeMillis(TimeUnit.MINUTES.toMillis(5));
    cfg.setMaxTotal(getMaxConnPoolSize());
    cfg.setMinIdle(getMinConnPoolSize());

    if (nodes.size() == 1) {
        return ConnectionPoolSupport.createGenericObjectPool(
            () -> client.connect(codec, RedisURI.create(nodes.get(0))),
            cfg
        );
    } else {
        List<RedisURI> uris = nodes.stream()
            .map(RedisURI::create)
            .collect(Collectors.toList());
        return ConnectionPoolSupport.createGenericObjectPool(
            () -> {
                StatefulRedisMasterReplicaConnection<String, Object> connection =
                    MasterReplica.connect(client, codec, uris);
                connection.setReadFrom(ReadFrom.MASTER_PREFERRED);
                return connection;
            },
            cfg
        );
    }
}
 
Example #27
Source File: RequiresRedisServer.java    From spring-data-examples with Apache License 2.0 5 votes vote down vote up
@Override
protected void before() throws Throwable {

	try (Socket socket = new Socket()) {
		socket.setTcpNoDelay(true);
		socket.setSoLinger(true, 0);
		socket.connect(new InetSocketAddress(host, port), timeout);
	} catch (Exception e) {
		throw new AssumptionViolatedException(String.format("Seems as Redis is not running at %s:%s.", host, port), e);
	}

	if (NO_VERSION.equals(requiredVersion)) {
		return;
	}

	RedisClient redisClient = RedisClient.create(ManagedClientResources.getClientResources(),
			RedisURI.create(host, port));

	try (StatefulRedisConnection<String, String> connection = redisClient.connect()) {

		String infoServer = connection.sync().info("server");
		String redisVersion = LettuceConverters.stringToProps().convert(infoServer).getProperty("redis_version");
		Version runningVersion = Version.parse(redisVersion);

		if (runningVersion.isLessThan(requiredVersion)) {
			throw new AssumptionViolatedException(String
					.format("This test requires Redis version %s but you run version %s", requiredVersion, runningVersion));
		}

	} finally {
		redisClient.shutdown(Duration.ZERO, Duration.ZERO);
	}
}
 
Example #28
Source File: RequiresRedisSentinel.java    From spring-data-examples with Apache License 2.0 5 votes vote down vote up
private boolean isAvailable(RedisNode node) {

		RedisClient redisClient = RedisClient.create(ManagedClientResources.getClientResources(),
				RedisURI.create(node.getHost(), node.getPort()));

		try (StatefulRedisConnection<String, String> connection = redisClient.connect()) {
			connection.sync().ping();
		} catch (Exception e) {
			return false;
		} finally {
			redisClient.shutdown(Duration.ZERO, Duration.ZERO);
		}

		return true;
	}
 
Example #29
Source File: LuaScriptIsolationTest.java    From bucket4j with Apache License 2.0 5 votes vote down vote up
@Before
public void init() {
    RedisURI url = RedisURI.Builder
            .redis(redis.getContainerIpAddress(), redis.getMappedPort(6379))
            .build();

    RedisClient client = RedisClient.create(url);
    StatefulRedisConnection<String, String> connection = client.connect();

    this.commands = connection.sync();
}
 
Example #30
Source File: StringStringSyncTest.java    From hazelcast-simulator with Apache License 2.0 5 votes vote down vote up
@Prepare(global = true)
public void loadInitialData() {
    Random random = new Random();
    StatefulRedisConnection<String, String> connection = redisClient.connect();
    RedisCommands sync = connection.sync();
    for (int k = 0; k < keyDomain; k++) {
        int r = random.nextInt(valueCount);
        sync.set(Long.toString(k), values[r]);
    }
}