当前位置: 代码网 > it编程>编程语言>Java > SpringBoot连接Redis集群教程

SpringBoot连接Redis集群教程

2025年06月20日 Java 我要评论
1. 依赖 <dependency> <groupid>redis.clients</groupid> <artifacti

1. 依赖

    <dependency>
        <groupid>redis.clients</groupid>
        <artifactid>jedis</artifactid>
    </dependency>

2. 修改配置文件

server.port=100

#redis集群节点信息
spring.redis.cluster.nodes=192.168.25.132:6379,192.168.25.132:6380,192.168.25.133:6379,192.168.25.133:6380,192.168.25.134:6379,192.168.25.134:6380
#redis连接密码(默认空)
spring.redis.password=
#redis连接池最大连接数(使用负值表示没有限制)
spring.redis.jedis.pool.max-active=20
#redis连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.jedis.pool.max-wait=-1
#redis连接池最大空闲连接
spring.redis.jedis.pool.max-idle=200
#redis连接池最小空闲连接
spring.redis.jedis.pool.min-idle=20
#redis连接超时时间(毫秒)
spring.redis.timeout=10000

3. 创建redisclusterconfig

@configuration
public class redisclusterconfig {

    @value("${spring.redis.cluster.nodes}")
    private string clusternodes;

    @value("${spring.redis.database}")
    private int database;

    @value("${spring.redis.timeout}")
    private int timeout;

    @value("${spring.redis.jedis.pool.max-idle}")
    private int maxidle;

    @value("${spring.redis.jedis.pool.min-idle}")
    private int minidle;

    @value("${spring.redis.jedis.pool.max-active}")
    private int maxactive;

    @value("${spring.redis.jedis.pool.max-wait}")
    private long maxwait;

    @bean
    public jediscluster getjediscluster() {
        return new jediscluster(getnodes(), timeout, poolconfig());
    }

    private jedispoolconfig poolconfig() {
        jedispoolconfig config = new jedispoolconfig();
        config.setmaxidle(maxidle);
        config.setminidle(minidle);
        config.setmaxtotal(maxactive);
        config.setmaxwaitmillis(maxwait);
        return config;
    }

    private set<hostandport> getnodes() {
        string[] cnodes = clusternodes.split(",");
        set<hostandport> nodes = new hashset<hostandport>();
        // 分割出集群节点
        string[] hp;
        for (string node : cnodes) {
            hp = node.split(":");
            nodes.add(new hostandport(hp[0], integer.parseint(hp[1])));
        }
        return nodes;
    }
}

4. 测试

@restcontroller
@requestmapping("/redis/cluster")
public class redisclustercontroller {
    @autowired
    private jediscluster jediscluster;

    @getmapping("/set")
    public void set(@requestparam("key") string key, @requestparam("value") string value){
        jediscluster.set(key, value);
    }
}

这边就不演示了,分别访问以下2个地址,能得到结果说明正常:

http://localhost:100/redis/cluster/set?key=name&value=zhangsan

http://localhost:100/redis/cluster/get?key=name

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com