基于Lettuce连接Redis单机和集群的客户端代码


SpringBoot 在封装 Lettuce 客户端代码到 spring-boot-starter-data-redis ,核心流程代码如下列举。

连接Redis单机

package com.example.demo.redis;

import io.lettuce.core.RedisClient;
import io.lettuce.core.RedisFuture;
import io.lettuce.core.RedisURI;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.api.async.RedisAsyncCommands;
import io.lettuce.core.api.sync.RedisCommands;
import lombok.extern.slf4j.Slf4j;

import java.time.Duration;
import java.util.concurrent.ExecutionException;

/**
 * 功能描述: 基于 Lettuce 框架连接单机 Redis
 *
 * @author geekziyu
 * @version 1.0.0
 */
@Slf4j
public class LettuceSingle {

    public static void main(String[] args) {
        // 步骤1:连接信息
        RedisURI redisURI = RedisURI.builder()
                .withHost("localhost")
                .withPort(6379)
                // .withPassword(new char[]{'a', 'b', 'c', '1', '2', '3'})
                .withTimeout(Duration.ofSeconds(10))
                .build();

        // 步骤2:创建Redis客户端
        RedisClient client = RedisClient.create(redisURI);

        // 步骤3:建立连接
        StatefulRedisConnection connection = client.connect();

        log.info("--------------------同步调用 BEGIN --------------------");
        // 异步转同步
        RedisCommands commands = connection.sync();
        // Redis命令:set hello world
        log.info("set hello world");
        String result = commands.set("hello", "world");
        log.info(result);

        log.info("get hello");
        result = commands.get("hello");
        log.info(result);
        log.info("--------------------同步调用 END --------------------");

        log.info("--------------------异步调用 BEGIN --------------------");
        RedisAsyncCommands asyncCommands = connection.async();
        log.info("get hello");
        RedisFuture future = asyncCommands.get("hello");

        try {
            result = future.get();
            log.info(result);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        } catch (ExecutionException e) {
            log.error("执行异常", e);
        }

        log.info("--------------------异步调用 END --------------------");

        connection.close();
        client.shutdown();

    }

}

连接Redis集群

package com.example.demo.redis;

import io.lettuce.core.RedisFuture;
import io.lettuce.core.RedisURI;
import io.lettuce.core.cluster.RedisClusterClient;
import io.lettuce.core.cluster.api.StatefulRedisClusterConnection;
import io.lettuce.core.cluster.api.async.RedisAdvancedClusterAsyncCommands;
import io.lettuce.core.cluster.api.sync.RedisAdvancedClusterCommands;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;

/**
 * 功能描述:基于 Lettuce 框架模拟连接 Redis 集群
 *
 * @author geekziyu
 * @version 1.0.0
 */
@Slf4j
public class LettuceCluster {

    public static void main(String[] args) {
        openCluster();
    }

    private static void openCluster() {
        // 步骤1:节点信息
        List servers = new ArrayList<>();
        servers.add(RedisURI.create("localhost", 6381));
        servers.add(RedisURI.create("localhost", 6382));
        servers.add(RedisURI.create("localhost", 6383));
        servers.add(RedisURI.create("localhost", 6384));
        servers.add(RedisURI.create("localhost", 6385));
        servers.add(RedisURI.create("localhost", 6386));

        // 步骤2:Redis集群客户端
        RedisClusterClient client = RedisClusterClient.create(servers);

        // 步骤3:建立连接
        StatefulRedisClusterConnection connection = client.connect();
        log.info("--------------------同步调用 BEGIN --------------------");
        // 异步转同步
        RedisAdvancedClusterCommands commands = connection.sync();
        // Redis命令:set hello world
        log.info("set hello world");
        String result = commands.set("hello", "world");
        log.info(result);

        log.info("get hello");
        result = commands.get("hello");
        log.info(result);
        log.info("--------------------同步调用 END --------------------");

        log.info("--------------------异步调用 BEGIN --------------------");
        RedisAdvancedClusterAsyncCommands asyncCommands = connection.async();
        log.info("get hello");
        RedisFuture future = asyncCommands.get("hello");

        try {
            result = future.get();
            log.info(result);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        } catch (ExecutionException e) {
            log.error("执行异常", e);
        }

        log.info("--------------------异步调用 END --------------------");

        connection.close();
        client.shutdown();
    }
}

其他文件

pom.xml

<?xml version="1.0" encoding="UTF-8"?>

  4.0.0
  
    org.springframework.boot
    spring-boot-starter-parent
    2.5.8
     
  
  com.example.demo.redis
  spring-boot-redis-connections
  0.0.1-SNAPSHOT
  spring-boot-redis-connections
  Demo project for Spring Boot
  
    1.8
    1.7.32
    1.2.6
  
  
    
      org.springframework.boot
      spring-boot-starter
    

    
      org.springframework.boot
      spring-boot-starter-web
    

    
      org.springframework.boot
      spring-boot-starter-data-redis
    

    
      org.projectlombok
      lombok
      true
    
    
      org.slf4j
      slf4j-api
      ${slf4j.version}
    
    
      ch.qos.logback
      logback-classic
      ${logback.version}
    

    
      org.springframework.boot
      spring-boot-starter-test
      test
    
  

  
    
      
        org.springframework.boot
        spring-boot-maven-plugin
      
    
  


logback.xml

<?xml version="1.0" encoding="UTF-8"?>

  
    
      %d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n