Skip to content

Commit 29750f4

Browse files
DOC-4543 started splitting Lettuce page
1 parent bd90eda commit 29750f4

File tree

2 files changed

+254
-115
lines changed

2 files changed

+254
-115
lines changed

content/develop/clients/lettuce.md renamed to content/develop/clients/lettuce/_index.md

Lines changed: 18 additions & 115 deletions
Original file line numberDiff line numberDiff line change
@@ -51,135 +51,38 @@ If you wish to use the JAR files directly, download the latest Lettuce and, opti
5151

5252
To build from source, see the instructions on the [Lettuce source code GitHub repo](https://github.com/lettuce-io/lettuce-core).
5353

54-
## Connect
54+
## Connect and test
5555

56-
Start by creating a connection to your Redis server. There are many ways to achieve this using Lettuce. Here are a few.
57-
58-
### Asynchronous connection
56+
Connect to a local server using the following code. This example
57+
also stores and retrieves a simple string value to test the connection.
5958

6059
```java
61-
package org.example;
62-
import java.util.*;
63-
import java.util.concurrent.ExecutionException;
64-
6560
import io.lettuce.core.*;
66-
import io.lettuce.core.api.async.RedisAsyncCommands;
6761
import io.lettuce.core.api.StatefulRedisConnection;
62+
import io.lettuce.core.api.sync.RedisCommands;
6863

69-
public class Async {
70-
public static void main(String[] args) {
71-
RedisClient redisClient = RedisClient.create("redis://localhost:6379");
72-
73-
try (StatefulRedisConnection<String, String> connection = redisClient.connect()) {
74-
RedisAsyncCommands<String, String> asyncCommands = connection.async();
75-
76-
// Asynchronously store & retrieve a simple string
77-
asyncCommands.set("foo", "bar").get();
78-
System.out.println(asyncCommands.get("foo").get()); // prints bar
79-
80-
// Asynchronously store key-value pairs in a hash directly
81-
Map<String, String> hash = new HashMap<>();
82-
hash.put("name", "John");
83-
hash.put("surname", "Smith");
84-
hash.put("company", "Redis");
85-
hash.put("age", "29");
86-
asyncCommands.hset("user-session:123", hash).get();
87-
88-
System.out.println(asyncCommands.hgetall("user-session:123").get());
89-
// Prints: {name=John, surname=Smith, company=Redis, age=29}
90-
} catch (ExecutionException | InterruptedException e) {
91-
throw new RuntimeException(e);
92-
} finally {
93-
redisClient.shutdown();
94-
}
95-
}
96-
}
97-
```
64+
public class ConnectBasicTest {
9865

99-
Learn more about asynchronous Lettuce API in [the reference guide](https://redis.github.io/lettuce/#asynchronous-api).
66+
public void connectBasic() {
67+
RedisURI uri = RedisURI.Builder
68+
.redis("localhost", 6379)
69+
.build();
70+
71+
RedisClient client = RedisClient.create(uri);
72+
StatefulRedisConnection<String, String> connection = client.connect();
73+
RedisCommands<String, String> commands = connection.sync();
10074

101-
### Reactive connection
75+
commands.set("foo", "bar");
76+
String result = commands.get("foo");
77+
System.out.println(result); // >>> bar
10278

103-
```java
104-
package org.example;
105-
import java.util.*;
106-
import io.lettuce.core.*;
107-
import io.lettuce.core.api.reactive.RedisReactiveCommands;
108-
import io.lettuce.core.api.StatefulRedisConnection;
79+
connection.close();
10980

110-
public class Main {
111-
public static void main(String[] args) {
112-
RedisClient redisClient = RedisClient.create("redis://localhost:6379");
113-
114-
try (StatefulRedisConnection<String, String> connection = redisClient.connect()) {
115-
RedisReactiveCommands<String, String> reactiveCommands = connection.reactive();
116-
117-
// Reactively store & retrieve a simple string
118-
reactiveCommands.set("foo", "bar").block();
119-
reactiveCommands.get("foo").doOnNext(System.out::println).block(); // prints bar
120-
121-
// Reactively store key-value pairs in a hash directly
122-
Map<String, String> hash = new HashMap<>();
123-
hash.put("name", "John");
124-
hash.put("surname", "Smith");
125-
hash.put("company", "Redis");
126-
hash.put("age", "29");
127-
128-
reactiveCommands.hset("user-session:124", hash).then(
129-
reactiveCommands.hgetall("user-session:124")
130-
.collectMap(KeyValue::getKey, KeyValue::getValue).doOnNext(System.out::println))
131-
.block();
132-
// Prints: {surname=Smith, name=John, company=Redis, age=29}
133-
134-
} finally {
135-
redisClient.shutdown();
81+
client.shutdown();
13682
}
137-
}
13883
}
13984
```
14085

141-
Learn more about reactive Lettuce API in [the reference guide](https://redis.github.io/lettuce/#reactive-api).
142-
143-
### Redis Cluster connection
144-
145-
```java
146-
import io.lettuce.core.RedisURI;
147-
import io.lettuce.core.cluster.RedisClusterClient;
148-
import io.lettuce.core.cluster.api.StatefulRedisClusterConnection;
149-
import io.lettuce.core.cluster.api.async.RedisAdvancedClusterAsyncCommands;
150-
151-
// ...
152-
153-
RedisURI redisUri = RedisURI.Builder.redis("localhost").withPassword("authentication").build();
154-
155-
RedisClusterClient clusterClient = RedisClusterClient.create(redisUri);
156-
StatefulRedisClusterConnection<String, String> connection = clusterClient.connect();
157-
RedisAdvancedClusterAsyncCommands<String, String> commands = connection.async();
158-
159-
// ...
160-
161-
connection.close();
162-
clusterClient.shutdown();
163-
```
164-
165-
### TLS connection
166-
167-
When you deploy your application, use TLS and follow the [Redis security guidelines]({{< relref "/operate/oss_and_stack/management/security/" >}}).
168-
169-
```java
170-
RedisURI redisUri = RedisURI.Builder.redis("localhost")
171-
.withSsl(true)
172-
.withPassword("secret!") // use your Redis password
173-
.build();
174-
175-
RedisClient client = RedisClient.create(redisUri);
176-
```
177-
178-
## Connection Management in Lettuce
179-
180-
Lettuce uses `ClientResources` for efficient management of shared resources like event loop groups and thread pools.
181-
For connection pooling, Lettuce leverages `RedisClient` or `RedisClusterClient`, which can handle multiple concurrent connections efficiently.
182-
18386
### Timeouts
18487

18588
Lettuce provides timeouts for many operations, such as command execution, SSL handshake, and Sentinel discovery. By default, Lettuce uses a global timeout value of 60 seconds for these operations, but you can override the global timeout value with individual timeout values for each operation.
Lines changed: 236 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,236 @@
1+
---
2+
categories:
3+
- docs
4+
- develop
5+
- stack
6+
- oss
7+
- rs
8+
- rc
9+
- oss
10+
- kubernetes
11+
- clients
12+
description: Connect your .NET application to a Redis database
13+
linkTitle: Connect
14+
title: Connect to the server
15+
weight: 2
16+
---
17+
18+
Start by creating a connection to your Redis server. There are many ways to achieve this using Lettuce. Here are a few.
19+
20+
## Basic connection
21+
22+
```java
23+
import io.lettuce.core.*;
24+
import io.lettuce.core.api.StatefulRedisConnection;
25+
import io.lettuce.core.api.sync.RedisCommands;
26+
27+
public class ConnectBasicTest {
28+
29+
public void connectBasic() {
30+
RedisURI uri = RedisURI.Builder
31+
.redis("localhost", 6379)
32+
.withAuthentication("default", "yourPassword")
33+
.build();
34+
RedisClient client = RedisClient.create(uri);
35+
StatefulRedisConnection<String, String> connection = client.connect();
36+
RedisCommands<String, String> commands = connection.sync();
37+
38+
commands.set("foo", "bar");
39+
String result = commands.get("foo");
40+
System.out.println(result); // >>> bar
41+
42+
connection.close();
43+
44+
client.shutdown();
45+
}
46+
}
47+
```
48+
49+
### Asynchronous connection
50+
51+
```java
52+
package org.example;
53+
import java.util.*;
54+
import java.util.concurrent.ExecutionException;
55+
56+
import io.lettuce.core.*;
57+
import io.lettuce.core.api.async.RedisAsyncCommands;
58+
import io.lettuce.core.api.StatefulRedisConnection;
59+
60+
public class Async {
61+
public static void main(String[] args) {
62+
RedisClient redisClient = RedisClient.create("redis://localhost:6379");
63+
64+
try (StatefulRedisConnection<String, String> connection = redisClient.connect()) {
65+
RedisAsyncCommands<String, String> asyncCommands = connection.async();
66+
67+
// Asynchronously store & retrieve a simple string
68+
asyncCommands.set("foo", "bar").get();
69+
System.out.println(asyncCommands.get("foo").get()); // prints bar
70+
71+
// Asynchronously store key-value pairs in a hash directly
72+
Map<String, String> hash = new HashMap<>();
73+
hash.put("name", "John");
74+
hash.put("surname", "Smith");
75+
hash.put("company", "Redis");
76+
hash.put("age", "29");
77+
asyncCommands.hset("user-session:123", hash).get();
78+
79+
System.out.println(asyncCommands.hgetall("user-session:123").get());
80+
// Prints: {name=John, surname=Smith, company=Redis, age=29}
81+
} catch (ExecutionException | InterruptedException e) {
82+
throw new RuntimeException(e);
83+
} finally {
84+
redisClient.shutdown();
85+
}
86+
}
87+
}
88+
```
89+
90+
Learn more about asynchronous Lettuce API in [the reference guide](https://redis.github.io/lettuce/#asynchronous-api).
91+
92+
### Reactive connection
93+
94+
```java
95+
package org.example;
96+
import java.util.*;
97+
import io.lettuce.core.*;
98+
import io.lettuce.core.api.reactive.RedisReactiveCommands;
99+
import io.lettuce.core.api.StatefulRedisConnection;
100+
101+
public class Main {
102+
public static void main(String[] args) {
103+
RedisClient redisClient = RedisClient.create("redis://localhost:6379");
104+
105+
try (StatefulRedisConnection<String, String> connection = redisClient.connect()) {
106+
RedisReactiveCommands<String, String> reactiveCommands = connection.reactive();
107+
108+
// Reactively store & retrieve a simple string
109+
reactiveCommands.set("foo", "bar").block();
110+
reactiveCommands.get("foo").doOnNext(System.out::println).block(); // prints bar
111+
112+
// Reactively store key-value pairs in a hash directly
113+
Map<String, String> hash = new HashMap<>();
114+
hash.put("name", "John");
115+
hash.put("surname", "Smith");
116+
hash.put("company", "Redis");
117+
hash.put("age", "29");
118+
119+
reactiveCommands.hset("user-session:124", hash).then(
120+
reactiveCommands.hgetall("user-session:124")
121+
.collectMap(KeyValue::getKey, KeyValue::getValue).doOnNext(System.out::println))
122+
.block();
123+
// Prints: {surname=Smith, name=John, company=Redis, age=29}
124+
125+
} finally {
126+
redisClient.shutdown();
127+
}
128+
}
129+
}
130+
```
131+
132+
Learn more about reactive Lettuce API in [the reference guide](https://redis.github.io/lettuce/#reactive-api).
133+
134+
## Connect to a Redis cluster
135+
136+
```java
137+
import io.lettuce.core.RedisURI;
138+
import io.lettuce.core.cluster.RedisClusterClient;
139+
import io.lettuce.core.cluster.api.StatefulRedisClusterConnection;
140+
import io.lettuce.core.cluster.api.async.RedisAdvancedClusterAsyncCommands;
141+
142+
// ...
143+
144+
RedisURI redisUri = RedisURI.Builder.redis("localhost").withPassword("authentication").build();
145+
146+
RedisClusterClient clusterClient = RedisClusterClient.create(redisUri);
147+
StatefulRedisClusterConnection<String, String> connection = clusterClient.connect();
148+
RedisAdvancedClusterAsyncCommands<String, String> commands = connection.async();
149+
150+
// ...
151+
152+
connection.close();
153+
clusterClient.shutdown();
154+
```
155+
156+
### TLS connection
157+
158+
When you deploy your application, use TLS and follow the [Redis security guidelines]({{< relref "/operate/oss_and_stack/management/security/" >}}).
159+
160+
```java
161+
RedisURI redisUri = RedisURI.Builder.redis("localhost")
162+
.withSsl(true)
163+
.withPassword("secret!") // use your Redis password
164+
.build();
165+
166+
RedisClient client = RedisClient.create(redisUri);
167+
```
168+
169+
## Connection Management in Lettuce
170+
171+
Lettuce uses `ClientResources` for efficient management of shared resources like event loop groups and thread pools.
172+
For connection pooling, Lettuce leverages `RedisClient` or `RedisClusterClient`, which can handle multiple concurrent connections efficiently.
173+
174+
## Connection pooling
175+
176+
A typical approach with Lettuce is to create a single `RedisClient` instance and reuse it to establish connections to your Redis server(s).
177+
These connections are multiplexed; that is, multiple commands can be run concurrently over a single or a small set of connections, making explicit pooling less practical.
178+
See
179+
[Connection pools and multiplexing]({{< relref "/develop/connect/clients/pools-and-muxing" >}})
180+
for more information.
181+
182+
Lettuce provides pool config to be used with Lettuce asynchronous connection methods.
183+
184+
```java
185+
package org.example;
186+
import io.lettuce.core.RedisClient;
187+
import io.lettuce.core.RedisURI;
188+
import io.lettuce.core.TransactionResult;
189+
import io.lettuce.core.api.StatefulRedisConnection;
190+
import io.lettuce.core.api.async.RedisAsyncCommands;
191+
import io.lettuce.core.codec.StringCodec;
192+
import io.lettuce.core.support.*;
193+
194+
import java.util.concurrent.CompletableFuture;
195+
import java.util.concurrent.CompletionStage;
196+
197+
public class Pool {
198+
public static void main(String[] args) {
199+
RedisClient client = RedisClient.create();
200+
201+
String host = "localhost";
202+
int port = 6379;
203+
204+
CompletionStage<BoundedAsyncPool<StatefulRedisConnection<String, String>>> poolFuture
205+
= AsyncConnectionPoolSupport.createBoundedObjectPoolAsync(
206+
() -> client.connectAsync(StringCodec.UTF8, RedisURI.create(host, port)),
207+
BoundedPoolConfig.create());
208+
209+
// await poolFuture initialization to avoid NoSuchElementException: Pool exhausted when starting your application
210+
AsyncPool<StatefulRedisConnection<String, String>> pool = poolFuture.toCompletableFuture()
211+
.join();
212+
213+
// execute work
214+
CompletableFuture<TransactionResult> transactionResult = pool.acquire()
215+
.thenCompose(connection -> {
216+
217+
RedisAsyncCommands<String, String> async = connection.async();
218+
219+
async.multi();
220+
async.set("key", "value");
221+
async.set("key2", "value2");
222+
System.out.println("Executed commands in pipeline");
223+
return async.exec().whenComplete((s, throwable) -> pool.release(connection));
224+
});
225+
transactionResult.join();
226+
227+
// terminating
228+
pool.closeAsync();
229+
230+
// after pool completion
231+
client.shutdownAsync();
232+
}
233+
}
234+
```
235+
236+
In this setup, `LettuceConnectionFactory` is a custom class you would need to implement, adhering to Apache Commons Pool's `PooledObjectFactory` interface, to manage lifecycle events of pooled `StatefulRedisConnection` objects.

0 commit comments

Comments
 (0)