redisson在redis集群方式中的配置

1,springboot集成redisson的时候,当redis为单节点时,直需要引入redisson的jar即可使用。

<dependency>
	<groupId>org.redisson</groupId>
	<artifactId>redisson-spring-boot-starter</artifactId>
	<version>3.11.4</version>
</dependency>

附:redisLockUtils代码

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * Created by KS15432 on 2021/11/11.
 */
@Component
public class RedisLockUtil {
    private final Logger logger = LoggerFactory.getLogger(RedisLockUtil.class);

    @Autowired
    private RedissonClient redissonClient;

   /* @Autowired
    public RedisLockUtil(@Qualifier("customRedisson") RedissonClient redissonClient) {
        this.redissonClient = redissonClient;
    }*/

    /**
     * 加锁
     * @param key 锁的 key
     * @param value  value ( key + value 必须保证唯一)
     * @param expire key 的过期时间,单位 ms
     * @param retryTimes 重试次数,即加锁失败之后的重试次数
     * @param retryInterval 重试时间间隔,单位 ms
     * @return 加锁 true 成功
     */
    public RLock lock(String key, String value, long expire, int retryTimes, long retryInterval) {
        logger.info("locking... redisK = {}", key);
        RLock fairLock = redissonClient.getFairLock(key + ":" +  value);
        try {
            boolean tryLock = fairLock.tryLock(0, expire, TimeUnit.MILLISECONDS);
            if (tryLock) {
                logger.info("locked... redisK = {}", key);
                return fairLock;
            } else {
                //重试获取锁
                logger.info("retry to acquire lock: [redisK = {}]", key);
                int count = 0;
                while(count < retryTimes) {
                    try {
                        Thread.sleep(retryInterval);
                        tryLock = fairLock.tryLock(0, expire, TimeUnit.MILLISECONDS);
                        if(tryLock) {
                            logger.info("locked... redisK = {}", key);
                            return fairLock;
                        }
                        logger.warn("{} times try to acquire lock", count + 1);
                        count++;
                    } catch (Exception e) {
                        logger.error("acquire redis occurred an exception", e);
                        break;
                    }
                }

                logger.info("fail to acquire lock {}", key);
            }
        } catch (Throwable e1) {
            logger.error("acquire redis occurred an exception", e1);
        }

        return fairLock;
    }

    /**
     * 加锁
     * @param key 锁的 key
     * @param value  value ( key + value 必须保证唯一)
     * @param expire key 的过期时间,单位 ms
     * @param retryTimes 重试次数,即加锁失败之后的重试次数
     * @param retryInterval 重试时间间隔,单位 ms
     * @return 加锁 true 成功
     */
    public boolean lock2(String key, String value, long expire, int retryTimes, long retryInterval) {
        logger.info("locking... redisK = {}", key);
        RLock fairLock = redissonClient.getFairLock(key + ":" +  value);
        try {
            boolean tryLock = fairLock.tryLock(0, expire, TimeUnit.MILLISECONDS);
            if (tryLock) {
                logger.info("locked... redisK = {}", key);
                return true;
            } else {
                //重试获取锁
                logger.info("retry to acquire lock: [redisK = {}]", key);
                int count = 0;
                while(count < retryTimes) {
                    try {
                        Thread.sleep(retryInterval);
                        tryLock = fairLock.tryLock(0, expire, TimeUnit.MILLISECONDS);
                        if(tryLock) {
                            logger.info("locked... redisK = {}", key);
                            return true;
                        }
                        logger.warn("{} times try to acquire lock", count + 1);
                        count++;
                    } catch (Exception e) {
                        logger.error("acquire redis occurred an exception", e);
                        break;
                    }
                }

                logger.info("fail to acquire lock {}", key);
                return false;
            }
        } catch (Throwable e1) {
            logger.error("acquire redis occurred an exception", e1);
            return false;
        }
    }


    /**
     * 加锁
     * @param key 锁的 key
     * @param value  value ( key + value 必须保证唯一)
     * @param expire key 的过期时间,单位 ms
     * @return 加锁 true 成功
     */
    public boolean lockCheck(String key, String value, long expire) {
        logger.info("locking... redisK = {}", key);
        RLock fairLock = redissonClient.getFairLock(key + ":" +  value);
        boolean tryLock = false;
        try {
            tryLock = fairLock.tryLock(0, expire, TimeUnit.MILLISECONDS);
        } catch (Throwable e1) {
            logger.error("acquire redis occurred an exception", e1);
        }
        return tryLock;
    }

    /**
     * 释放KEY
     * @return 释放锁 true 成功
     */
    public boolean unlock(String key, String value) {
        RLock fairLock = redissonClient.getFairLock(key + ":" +  value);
        try {
            //如果这里抛异常,后续锁无法释放
            if (fairLock.isLocked()) {
                fairLock.unlock();
                logger.info("release lock success");

                return true;
            }
        } catch (Throwable e) {
            logger.error("release lock occurred an exception", e);
        }

        return false;
    }
}

2,当redis为集群模式时,即springboot配置文件为这种cluster配置时,此时用redisson会出现错误。

redis:
      cluster:
        nodes: 10.200.56.89:6379,10.200.56.89:6380,10.200.56.89:6381,10.200.56.93:6379,10.200.56.93:6380,10.200.56.93:6381

需要增加配置文件:RedissonConfiguration


import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.ClusterServersConfig;
import org.redisson.config.Config;
import org.redisson.config.SingleServerConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Configuration
public class RedissonConfiguration {

    @Autowired
    private RedisProperties redisProperties;
    /**
     * 初始化RedissonClient客户端
     * 注意:
     * 此实例集群为3节点,各节点1主1从
     * 集群模式,集群节点的地址须使用“redis://”前缀,否则将会报错。
     *
     * @return {@link RedissonClient}
     */
    @Bean
    public RedissonClient getRedissonClient() {
        Config config = new Config();
        if (redisProperties.getCluster() != null) {
            //集群模式配置
            List<String> nodes = redisProperties.getCluster().getNodes();

            List<String> clusterNodes = new ArrayList<>();
            for (int i = 0; i < nodes.size(); i++) {
                clusterNodes.add("redis://" + nodes.get(i));
            }
            ClusterServersConfig clusterServersConfig = config.useClusterServers()
                    .addNodeAddress(clusterNodes.toArray(new String[clusterNodes.size()]));

            if (!StringUtils.isEmpty(redisProperties.getPassword())) {
                clusterServersConfig.setPassword(redisProperties.getPassword());
            }
        } else {
            //单节点配置
            String address = "redis://" + redisProperties.getHost() + ":" + redisProperties.getPort();
            SingleServerConfig serverConfig = config.useSingleServer();
            serverConfig.setAddress(address);
            if (!StringUtils.isEmpty(redisProperties.getPassword())) {
                serverConfig.setPassword(redisProperties.getPassword());
            }
            serverConfig.setDatabase(redisProperties.getDatabase());
        }
        //看门狗的锁续期时间,默认30000ms,这里配置成15000ms
        config.setLockWatchdogTimeout(15000);
        return Redisson.create(config);
    }
}

注:其中部分代码有参考其他博文的地方,源地址已忘记,侵删,不好意思,谢谢。

如有错误的地方望指正,谢谢。

  • 7
    点赞
  • 33
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
1、什么是 Redis? 2、Redis 相比 memcached 有哪些优势? 3、Redis 支持哪几种数据类型? 4、Redis 主要消耗什么物理资源? 5、Redis 的全称是什么? 6、Redis 有哪几种数据淘汰策略? 7、Redis 官方为什么不提供 Windows 版本? 8、一个字符串类型的值能存储最大容量是多少? 9、为什么 Redis 需要把所有数据放到内存? 10、Redis 集群方案应该怎么做?都有哪些方案? 11、Redis 集群方案什么情况下会导致整个集群不可用? 12、MySQL 里有 2000w 数据,Redis 只存 20w 的数据, 如何保证 Redis 的数据都是热点数据? 13、Redis 有哪些适合的场景? 14、Redis 支持的 Java 客户端都有哪些?官方推荐用哪个? 15、RedisRedisson 有什么关系? 16、Jedis 与 Redisson 对比有什么优缺点? 17、Redis 如何设置密码及验证密码? 18、说说 Redis 哈希槽的概念? 19、Redis 集群的主从复制模型是怎样的? 20、Redis 集群会有写操作丢失吗?为什么? 21、Redis 集群之间是如何复制的? 22、Redis 集群最大节点个数是多少? 23、Redis 集群如何选择数据库? 24、怎么测试 Redis 的连通性? 25、Redis 的管道有什么用? 26、怎么理解 Redis 事务? 27、Redis 事务相关的命令有哪几个? 28、Redis key 的过期时间和永久有效分别怎么设置? 29、Redis 如何做内存优化? 30、Redis 回收进程如何工作的? 31、Redis 回收使用的是什么算法? 32、Redis 如何做大量数据插入? 33、为什么要做 Redis 分区? 34、你知道有哪些 Redis 分区实现方案? 35、Redis 分区有什么缺点? 36、Redis 持久化数据和缓存怎么做扩容? 37、分布式 Redis 是前期做还是后期规模上来了再做好?为 什么? 38、Twemproxy 是什么? 39、支持一致性哈希的客户端有哪些? 40、Redis 与其他 key-value 存储有什么不同? 41、Redis 的内存占用情况怎么样? 42、都有哪些办法可以降低 Redis 的内存使用情况呢? 43、查看 Redis 使用情况及状态信息用什么命令? 44、Redis 的内存用完了会发生什么? 45、Redis 是单线程的,如何提高多核 CPU 的利用率? 46、一个 Redis 实例最多能存放多少的 keys?List、Set、 Sorted Set 他们最多能存放多少元素? 47、Redis 常见性能问题和解决方案? 48、Redis 提供了哪几种持久化方式? 49、如何选择合适的持久化方式? 50、修改配置不重启 Redis 会实时生效吗?
回答: 要在Spring Boot集成Redisson连接Redis集群,你需要进行以下步骤。首先,你需要在pom.xml文件引入Redisson的依赖项,如下所示:\[2\] ```xml <dependency> <groupId>org.redisson</groupId> <artifactId>redisson</artifactId> <version>3.17.0</version> </dependency> ``` 接下来,你需要在配置文件进行相应的配置。你可以使用Redisson提供的配置类来配置Redis连接,例如使用`RedissonClusterConfig`来配置Redis集群连接。你可以在配置文件指定Redis集群的节点信息和其他相关配置。\[2\] 最后,你可以在Spring Boot应用程序使用Redisson的API来连接和操作Redis集群。你可以使用`RedissonClient`接口来获取Redis连接,并使用相应的方法来执行操作,如存储、读取和删除数据等。\[2\] 如果你想使用命令行来搭建Redis集群,你可以使用以下命令:\[3\] ``` redis-cli --cluster create 192.168.2.66:7000 192.168.2.66:7001 192.168.2.66:7002 192.168.2.66:7003 192.168.2.66:7004 192.168.2.66:7005 --cluster-replicas 1 ``` 这个命令将创建一个包含6个节点的Redis集群,并设置每个主节点有一个从节点。你需要根据你自己的实际情况修改IP地址和端口号。\[3\] 希望这些信息对你有帮助! #### 引用[.reference_title] - *1* *3* [SpringBoot整合Redisson操作集群redis](https://blog.csdn.net/u013658328/article/details/112661206)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [SpringBoot集成redisson操作redis](https://blog.csdn.net/quanzhan_King/article/details/130961128)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值