Spring Data Redis简单使用

Spring Data Redis是一个用于简化应用程序与Redis交互的开发框架。它提供了简单的配置和方便的操作API,使得与Redis的集成变得更加容易。下面是一个快速入门使用Spring Data Redis的步骤:

步骤 1:添加依赖

在您的项目中添加Spring Data Redis的依赖。可以在Maven项目中的pom.xml文件中添加以下依赖关系:

XML 复制代码
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
        </dependency>

步骤 2:配置Redis连接

在项目的配置文件中,配置Redis的连接信息。application.yml文件配置。

XML 复制代码
spring:
  data:
    redis:
      host: 127.0.0.1
      port: 6379
      database: 2
        # 连接超时
      connect-timeout: 5s
        # 读超时
      timeout: 5s

        # Lettuce 客户端的配置
      lettuce:
          # 连接池配置
          pool:
            # 最小空闲连接
            min-idle: 0
            # 最大空闲连接
            max-idle: 8
            # 最大活跃连接
            max-active: 8
            # 从连接池获取连接 最大超时时间,小于等于0则表示不会超时
            max-wait: -1ms

步骤 3:测试类里测试

java 复制代码
@SpringBootTest
class RedisApplicationTests {

    static final Logger logger = LoggerFactory.getLogger(RedisApplicationTests.class);
    // 注入 RedisTemplate
    @Autowired
    RedisTemplate RedisTemplate;

    @Test
    public void test() {
        // Map
        Map<String, Object> map = new HashMap<>();
        map.put("title", "spring-data-redis");
        map.put("url", "https://spring.io/projects/spring-data-redis");
        map.put("createAt", LocalDateTime.now());

        // 设置 key/value
        RedisTemplate.opsForValue().set("key1-string", map, Duration.ofMinutes(5));
        // 读取 key/value
        map = (Map<String, Object>) RedisTemplate.opsForValue().get("key1-string");
        logger.info("map={}", map);

        // 设置 Hash Value
        RedisTemplate.opsForHash().put("key2-hash", "app", map);
        // 读取 Hash Value
        map = (Map<String, Object>) RedisTemplate.opsForHash().get("key2-hash", "app");

        logger.info("map={}", map);
    }

}

redis面试题:

经典20道面试题

链接:

ZSET 的经典使用场景是用来实现排行榜

链接: 【Redis面试题】如何使用Redis实现微信步数排行榜? - 知乎.

Redis主从复制原理总结

链接: https://www.cnblogs.com/daofaziran/p/10978628.html.

Redis是单线程的为什么速度还这么快?

链接: https://www.cnblogs.com/fengli9998/p/12092375.html.

Redis集群选举机制

链接: redis集群选举机制-CSDN博客.

Redisson实现Redis分布式锁的原理

链接: https://www.cnblogs.com/AnXinliang/p/10019389.html.

相关推荐
咖啡八杯1 天前
GoF设计模式——备忘录模式
java·后端·spring·设计模式
vivo互联网技术2 天前
从 10 分钟到 1 秒:ES 深度分页任意跳页的三轮优化实战
服务器·数据库·redis·elasticsearch·深度分页
Flittly3 天前
【AgentScope Java新手村系列】(16)从RAG到多路检索
java·spring boot·spring
咖啡八杯3 天前
GoF设计模式——中介者模式
java·后端·spring·设计模式
用户3074596982075 天前
Redis 延时队列详解
redis
烤代码的吐司君5 天前
Redis 数据结构 ZSet, BIT, HyperLogLog,Geo 空间数据
redis·后端
Flittly5 天前
【AgentScope Java新手村系列】(14)人机交互
java·spring boot·spring
leeyi7 天前
Checkpoint 机制:Agent 怎么在断电后接着跑
redis·aigc·agent
云技纵横8 天前
一个 @Async 让循环依赖暴雷:Spring 代理的暗坑
redis