springboot整合redisson单机模式

springboot整合redisson单机模式

文档

  1. redis单机安装
  2. redis常用的五种数据类型
  3. springboot整合redis-RedisTemplate单机模式
  4. 布隆过滤器 -Bloom Filter

官方文档

  1. 官网操作命令指南页面:https://redis.io/docs/latest/commands/?name=get&group=string
  2. Redis cluster specification

说明

  1. redis版本:7.0.0
  2. springboot版本:3.2.0

springboot整合redisson单机模式

安装单机版redis
  1. 安装单机版redis参考文档:redis单机安装
方式1:手动创建RedissonClient
  1. 说明:用RedisProperties手动创建RedissonClient Bean,并且复用Spring的Redis配置

  2. 参考:springboot整合redis-RedisTemplate单机模式,配置application.yml配置文件

    yaml 复制代码
    spring:
      data:
        redis:
          database: 0
          host: 192.168.145.132
          port: 6379
          password: 123456
          client-type: lettuce
          lettuce:
            pool:
              max-active: 8
              max-wait: -1ms
              max-idle: 8
              min-idle: 0
    • 这里的配置是spring-boot-starter-data-redis的配置,一般情况下都会先引用Spring的redis。在这里,集成redisson时,复用Spring的Redis配置,手动创建RedissonClient
    • 实际上,集成redisson不必须依赖 Spring 的 spring-boot-starter-data-redis
  3. 引入依赖

    xml 复制代码
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
    
    <dependency>
        <groupId>org.redisson</groupId>
        <artifactId>redisson</artifactId>
        <version>3.37.0</version>
    </dependency>
    • spring-boot-starter-data-redis的版本号:3.2.0,与springboot版本一致
    • redisson的版本号:3.37.0
  4. RedissonConfig.java配置类创建RedissonClient Bean

    java 复制代码
    @Configuration
    @EnableConfigurationProperties(RedisProperties.class)
    public class RedissonConfig {
    
        private final RedisProperties redisProperties;
    
        public RedissonConfig(RedisProperties redisProperties) {
            this.redisProperties = redisProperties;
        }
    
        @Bean(destroyMethod = "shutdown")
        public RedissonClient redissonClient() {
            Config config = new Config();
    
            // 是否启用 SSL
            String prefix = "redis://";
    
            // 连接池参数(来自 spring.data.redis.lettuce.pool)
            RedisProperties.Pool pool = redisProperties.getLettuce() != null
                    ? redisProperties.getLettuce().getPool()
                    : null;
    
            SingleServerConfig singleServerConfig = config.useSingleServer()
                    .setAddress(prefix + redisProperties.getHost() + ":" + redisProperties.getPort())
                    .setDatabase(redisProperties.getDatabase());
    
            if (pool != null) {
                // max-active 对应 Redisson 的连接池大小
                singleServerConfig.setConnectionPoolSize(pool.getMaxActive());
                // min-idle 对应 Redisson 的最小空闲连接
                singleServerConfig.setConnectionMinimumIdleSize(pool.getMinIdle());
            }
    
            if (StringUtils.hasText(redisProperties.getPassword())) {
                singleServerConfig.setPassword(redisProperties.getPassword());
            }
    
            return Redisson.create(config);
        }
    }
方式2:引用redisson-spring-boot-starter,自动装配RedissonClient
配置连接信息
  1. 修改application.yml配置文件

    yaml 复制代码
    spring:
      data:
        redis:
          database: 0
          host: 192.168.145.132
          port: 6379
          password: 123456
          client-type: lettuce
          lettuce:
            pool:
              max-active: 8
              max-wait: -1ms
              max-idle: 8
              min-idle: 0
  2. 引入依赖

    xml 复制代码
    <dependency>
        <groupId>org.redisson</groupId>
        <artifactId>redisson-spring-boot-starter</artifactId>
        <version>3.37.0</version>
    </dependency>
    • spring-boot-starter-data-redis的版本号:3.2.0,与springboot版本一致
    • redisson-spring-boot-starter的版本号:3.37.0
  3. starter 会按 spring.data.redis.*自动创建 Redisson 单机客户端。

  4. 当需要集群、哨兵、连接池等更细的配置时,用独立 Redisson 配置文件

示例
  1. RedissonController.java中,注入RedissonClient对象来操作reids

    java 复制代码
    @RestController
    @RequestMapping("redisson")
    public class RedissonController {
    
        @Autowired
        private RedissonClient redissonClient;
    
        @GetMapping("redisson-test")
        public String redissonTest() {
            // ================== 1. 字符串 / 简单对象:RBucket ==================
            // 新增 / 更新
            RBucket<String> bucket = redissonClient.getBucket("test:string:key");
            bucket.set("hello redisson");              // 默认不过期
            // bucket.set("hello redisson", 10, TimeUnit.MINUTES); // 10 分钟过期
    
            // 查询
            String value = bucket.get();
    
            // 删除
            boolean deleted = bucket.delete();
    
            // ================== 2. Hash 结构:RMap ==================
            RMap<String, String> map = redissonClient.getMap("test:map:key");
    
            // 添加 / 修改
            map.put("name", "Tom");
            map.put("age", "18");
    
            // 查询单个字段
            String name = map.get("name");
    
            // 查询所有
            Map<String, String> all = new HashMap<>(map);
    
            // 删除字段
            map.remove("age");
    
            // 清空整个 map
            // map.delete();
    
            // ================== 3. 分布式锁:RLock(可选示例) ==================
            RLock lock = redissonClient.getLock("lock:test");
            try {
                // 尝试加锁,最多等待 3 秒,拿到锁后 10 秒自动释放
                if (lock.tryLock(3, 10, TimeUnit.SECONDS)) {
                    // 在这里执行业务逻辑(加锁保护的代码)
                    System.out.println("获取到锁,执行业务逻辑...");
                } else {
                    System.out.println("未获取到锁");
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            } finally {
                // 判断当前线程是否持有锁,避免误解锁
                if (lock.isHeldByCurrentThread()) {
                    lock.unlock();
                }
            }
    
            // 简单返回下结果,方便你在浏览器里看到
            return "bucketValue=" + value + ", bucketDeleted=" + deleted + ", mapName=" + name + ", mapSize=" + all.size();
        }
    }

参考资料

  1. https://www.bilibili.com/video/BV13R4y1v7sP

注意事项

  1. 部分内容由AI生成
  2. 如有不对,欢迎指正!!!
相关推荐
无心水2 小时前
【任务调度:数据库锁 + 线程池实战】3、 从 SELECT 到 UPDATE:深入理解 SKIP LOCKED 的锁机制与隔离级别
java·分布式·科技·spring·架构
编程小白gogogo3 小时前
苍穹外卖图片不显示解决教程
java·spring boot
舟舟亢亢3 小时前
算法总结——二叉树【hot100】(上)
java·开发语言·算法
百锦再3 小时前
Java中的char、String、StringBuilder与StringBuffer 深度详解
java·开发语言·python·struts·kafka·tomcat·maven
上进小菜猪4 小时前
基于 YOLOv8 的水体污染目标检测系统 [目标检测完整源码]
后端
努力努力再努力wz4 小时前
【Linux网络系列】:TCP 的秩序与策略:揭秘传输层如何从不可靠的网络中构建绝对可靠的通信信道
java·linux·开发语言·数据结构·c++·python·算法
yy.y--5 小时前
Java数组逆序读写文件实战
java·开发语言
BD_Marathon6 小时前
IDEA创建多级包时显示在同一行怎么办
java·ide·intellij-idea
亓才孓6 小时前
【Exception】CONDITIONS EVALUATION REPORT条件评估报告
java·开发语言·mybatis
山岚的运维笔记6 小时前
SQL Server笔记 -- 第72章:隔离级别与锁定
数据库·笔记·后端·sql·microsoft·sqlserver