• 基于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<String, String> connection = client.connect();
    
            log.info("--------------------同步调用 BEGIN --------------------");
            // 异步转同步
            RedisCommands<String, String> 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<String, String> asyncCommands = connection.async();
            log.info("get hello");
            RedisFuture<String> 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<RedisURI> 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<String, String> connection = client.connect();
            log.info("--------------------同步调用 BEGIN --------------------");
            // 异步转同步
            RedisAdvancedClusterCommands<String, String> 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<String, String> asyncCommands = connection.async();
            log.info("get hello");
            RedisFuture<String> 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"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0</modelVersion>
      <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.8</version>
        <relativePath/> <!-- lookup parent from repository -->
      </parent>
      <groupId>com.example.demo.redis</groupId>
      <artifactId>spring-boot-redis-connections</artifactId>
      <version>0.0.1-SNAPSHOT</version>
      <name>spring-boot-redis-connections</name>
      <description>Demo project for Spring Boot</description>
      <properties>
        <java.version>1.8</java.version>
        <slf4j.version>1.7.32</slf4j.version>
        <logback.version>1.2.6</logback.version>
      </properties>
      <dependencies>
        <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter</artifactId>
        </dependency>
    
        <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    
        <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
    
        <dependency>
          <groupId>org.projectlombok</groupId>
          <artifactId>lombok</artifactId>
          <optional>true</optional>
        </dependency>
        <dependency>
          <groupId>org.slf4j</groupId>
          <artifactId>slf4j-api</artifactId>
          <version>${slf4j.version}</version>
        </dependency>
        <dependency>
          <groupId>ch.qos.logback</groupId>
          <artifactId>logback-classic</artifactId>
          <version>${logback.version}</version>
        </dependency>
    
        <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-test</artifactId>
          <scope>test</scope>
        </dependency>
      </dependencies>
    
      <build>
        <plugins>
          <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
          </plugin>
        </plugins>
      </build>
    
    </project>
    

    logback.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <configuration>
      <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
          <pattern>%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n</pattern>
        </encoder>
      </appender>
    
      <root level="debug">
        <appender-ref ref="STDOUT"/>
      </root>
    </configuration>
    

    简单的get&set

    RedisConfig

    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.data.redis.connection.RedisConnectionFactory;
    import org.springframework.data.redis.core.RedisTemplate;
    import org.springframework.data.redis.serializer.StringRedisSerializer;
    
    @Configuration
    public class RedisConfiguration {
    
      @Bean
      public StringRedisSerializer stringRedisSerializer() {
        return new StringRedisSerializer();
      }
    
      @Bean
      public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> result = new RedisTemplate<>();
        result.setConnectionFactory(factory);
        result.setKeySerializer(stringRedisSerializer());
        result.setValueSerializer(stringRedisSerializer());
        result.setHashKeySerializer(stringRedisSerializer());
        result.setHashValueSerializer(stringRedisSerializer());
        return result;
      }
    
    }
    

    AdminController

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.data.redis.core.RedisTemplate;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    
    @RestController
    @RequestMapping("/admin")
    public class AdminController {
    
      @Autowired
      private RedisTemplate<String, Object> redisTemplate;
    
      @GetMapping("/get")
      public String get(String key) {
        Object result = redisTemplate.opsForValue().get(key);
        return String.valueOf(result);
      }
    
      @GetMapping("/set")
      public String set(String key, String value) {
        redisTemplate.opsForValue().set(key, value);
        return "ok";
      }
    }
    

    application.properties

    spring.redis.host=localhost
    spring.redis.port=6379
    
    #spring.redis.url=redis://user:password@example.com:6379
    #spring.redis.sentinel.master=localhost:26379
    #spring.redis.sentinel.nodes=localhost:26379,localhost:26380,localhost:26381
    
    #spring.redis.cluster.nodes=localhost:6381,localhost:6382,localhost:6383,localhost:6384,localhost:6385,localhost:6386
    #spring.redis.password=abc123
    
  • 相关阅读:
    【NOIP2011】观光公交
    【NOIP2014】飞扬的小鸟
    HDU
    [Tyvj 1728]普通平衡树
    【NOIP2012】 疫情控制
    洛谷P1613 跑路
    [HNOI2002]营业额统计
    3486 ( Interviewe )RMQ
    poj2019 二维RMQ裸题
    动态规划专题
  • 原文地址:https://www.cnblogs.com/kendoziyu/p/15845875.html
Copyright © 2020-2023  润新知