更新时间:2022-05-27 GMT+08:00
分享

Lettuce

介绍使用同一VPC内弹性云服务器ECS上的Lettuce连接Redis实例的方法。更多的客户端的使用方法请参考Redis客户端

前提条件

  • 已成功申请Redis实例,且状态为“运行中”。
  • 已创建弹性云服务器,创建弹性云服务器的方法,请参见创建弹性云服务器
  • 如果弹性云服务器为Linux系统,该弹性云服务器必须已经安装java编译环境。

操作步骤

  1. 查看并获取待连接Redis实例的IP地址/域名和端口。

    具体步骤请参见查看实例信息

  2. 登录弹性云服务器。
  3. 首先使用maven在pom.xml添加如下依赖。

    <dependency>
      <groupId>io.lettuce</groupId>
      <artifactId>lettuce-core</artifactId>
      <version>6.1.6.RELEASE</version>
    </dependency>

  4. 使用Redis Java (Lettuce)客户端连接实例。

    • Lettuce单连方式连接Redis单机、主备、proxy集群示例。
      // password是连接的密码,不需验证删除password@即可,密码中有特殊字符时需要进行转码
      RedisClient redisClient = RedisClient.create("redis://password@host:port");
      StatefulRedisConnection<String, String> connection = redisClient.connect();
      RedisCommands<String, String> syncCommands = connection.sync();
      syncCommands.set("key", "value");
      System.out.println("Connected to Redis:" + syncCommands.get("key"));
      // 连接关闭
      connection.close();
      // 客户端关闭
      redisClient.shutdown();
    • Lettuce连接池方式连接Redis单机、主备、proxy集群示例。
      1. 在以上maven依赖的基础上添加以下依赖。
        <dependency>  
           <groupId>org.apache.commons</groupId>  
           <artifactId>commons-pool2</artifactId>
            <version>2.11.1</version>  
         </dependency> 
      2. 具体代码如下。
        // password是连接的密码,不需验证删除password@即可,密码中有特殊字符时需要进行转码
        RedisClient clusterClient = RedisClient.create("redis://password@host:port");
        GenericObjectPoolConfig<StatefulRedisConnection<String, String>> genericObjectPoolConfig = new GenericObjectPoolConfig();
        // 连接池相关参数配置
        genericObjectPoolConfig.setMaxIdle(3);
        genericObjectPoolConfig.setMinIdle(2);
        genericObjectPoolConfig.setMaxTotal(3);
        genericObjectPoolConfig.setMaxWaitMillis(-1);
        GenericObjectPool<StatefulRedisConnection<String, String>> pool = ConnectionPoolSupport
                .createGenericObjectPool(() -> clusterClient.connect(), genericObjectPoolConfig);
        // 获取连接进行操作
        try (StatefulRedisConnection<String, String> con = pool.borrowObject()) {
            RedisCommands<String, String> sync = con.sync();
        	sync.set("key", "value");
            System.out.println("Connected by pool:" + sync.get("key"));
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            // 资源关闭
            pool.close();
            clusterClient.shutdown();
        }
    • Lettuce单连方式连接Redis cluster集群示例。(必须开启集群自动刷新拓扑配置)
      public class SingleConnectionToCluster {  
          public static void main(String[] args) {
               // 开启集群自动刷新拓扑  
              ClusterTopologyRefreshOptions topologyRefreshOptions = ClusterTopologyRefreshOptions.builder()  
                  .enablePeriodicRefresh(Duration.ofMillis(60000))  
                  .enableAllAdaptiveRefreshTriggers()  
                  .build();  
              // password是连接的密码,不需验证删除password@即可,密码中有特殊字符时需要进行转码  
              RedisClusterClient redisClient = RedisClusterClient.create("redis://password@host:port");  
              redisClient.setOptions(ClusterClientOptions.builder()  
                  .topologyRefreshOptions(topologyRefreshOptions)  
                  .build());  
              StatefulRedisClusterConnection<String, String> connection = redisClient.connect(); 
               // 优先从优先从副本读取
               connection.setReadFrom(ReadFrom.REPLICA_PREFERRED); 
              RedisAdvancedClusterCommands<String, String> syncCommands = connection.sync();  
              syncCommands.set("key", "value");  
              System.out.println("Connected to RedisCluster:" + syncCommands.get("key"));  
              // 连接关闭  
              connection.close();  
              // 客户端关闭  
              redisClient.shutdown();  
          }  
      }  
    • Lettuce连接池方式连接Redis cluster集群代码示例。
      1. 在以上maven依赖的基础上添加以下依赖。
        <dependency>  
           <groupId>org.apache.commons</groupId>  
           <artifactId>commons-pool2</artifactId>
            <version>2.11.1</version>  
         </dependency>  
      2. 具体代码如下。(必须开启集群自动刷新拓扑配置)
        public class PoolConnectionToCluster {  
            public static void main(String[] args) {
                 // 开启集群自动刷新拓扑  
                ClusterTopologyRefreshOptions topologyRefreshOptions = ClusterTopologyRefreshOptions.builder()  
                    .enablePeriodicRefresh(Duration.ofMillis(60000))  
                    .enableAllAdaptiveRefreshTriggers()  
                    .build();  
                // password是连接的密码,不需验证删除password@即可,密码中有特殊字符时需要进行转码  
                RedisClusterClient redisClient = RedisClusterClient.create("redis://password@host:port");  
                redisClient.setOptions(ClusterClientOptions.builder()  
                    .topologyRefreshOptions(topologyRefreshOptions)  
                    .build());  
                GenericObjectPoolConfig<StatefulRedisClusterConnection<String, String>> genericObjectPoolConfig  
                    = new GenericObjectPoolConfig();  
                // 连接池相关参数配置  
                genericObjectPoolConfig.setMaxIdle(3);  
                genericObjectPoolConfig.setMinIdle(2);  
                genericObjectPoolConfig.setMaxTotal(3);  
                genericObjectPoolConfig.setTimeBetweenEvictionRuns(Duration.ofMillis(2000));  
                genericObjectPoolConfig.setMaxWait(Duration.ofMillis(5000));  
                GenericObjectPool<StatefulRedisClusterConnection<String, String>> pool = ConnectionPoolSupport  
                    .createGenericObjectPool(() -> redisClient.connect(), genericObjectPoolConfig);  
                // 获取连接进行操作  
                try (StatefulRedisClusterConnection<String, String> con = pool.borrowObject()) {  
                     // 优先从优先从副本读取
                     con.setReadFrom(ReadFrom.REPLICA_PREFERRED);
                    RedisAdvancedClusterCommands<String, String> syncCommands = con.sync();  
                    syncCommands.set("key", "value");  
                    System.out.println("Connected to RedisCluster:" + syncCommands.get("key"));  
                } catch (Exception e) {  
                    e.printStackTrace();  
                } finally {  
                    // 资源关闭  
                    pool.close();  
                    redisClient.shutdown();  
                }  
            }  
        } 

    说明:host为Redis实例的IP地址/域名,port为Redis实例的端口,请按实际情况修改后执行,password为创建Redis实例时自定义的密码,请按实际情况修改后执行。推荐使用连接池方式;超时时间(timeout),最大连接数(MaxTotal),最小空闲连接(MinIdle),最大空闲连接(MaxIdle),最大等待时间(MaxWait)等相关参数,请根据业务实际来调优。

分享:

    相关文档

    相关产品

close