| 
 | 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