redis cluster集群安装 window, SpringBoot通过Jedis整合redis集群

1、redis安装

首先安装redis版本5及以上都行

安装地址 版本很多,记得选择正确版本

Index of /releases/

2、redis配置文件

注意:我是在一台机器上搭建的集群

(1)解压redis压缩包命名为redis6380,占到里面的redis.windows.conf文件修改以下配置

# todo 端口,如果你主机ip不一样,其实也可以不用改
port 6380

# todo 集群改为yes,开启AOF持久化
appendonly yes

# todo 是否开启集群
cluster-enabled yes

# todo 指定节点配置文件名,记得和端口号相同
cluster-config-file nodes-6380.conf

(2)完成上述操作后,复制redis6380五份,将文件名修改为redis6381,redis6382,redis6383,redis6384,redis6385

(3)修改其他redis6381,redis6382,redis6383,redis6384,redis6385中的redis.windows.conf文件中的端口号以及集群配置中的节点配置,如下

# todo 端口,如果你主机ip不一样,其实也可以不用改
port 6381

# todo 集群改为yes,开启AOF持久化
appendonly yes

# todo 是否开启集群
cluster-enabled yes

# todo 指定节点配置文件名,记得和端口号相同
cluster-config-file nodes-6381.conf

(4)、启动各个redis节点

rem "启动redis脚本"
D:
rem "redis节点的安装路径"
cd D:\ProgramFiles\redis-cloud-test\Redis6380
redis-server.exe redis.windows.conf

新建一个start.bat文件,将上述命令复制并修改其中的redis安装目录,双击start.bat文件,即可启动,再重复操作依次启动其他节点

3、启动集群

记得cmd命令窗口需要其中某个节点的redis.windows.conf文件的同级目录再执行,或者自己写个批处理脚本都行

redis-cli.exe  --cluster create --cluster-replicas 1 127.0.0.1:6380 127.0.0.1:6381 127.0.0.1:6382 127.0.0.1:6383 127.0.0.1:6384 127.0.0.1:6385

--cluster create集群创建命名

 --cluster-replicas 1 集群主节点的从节点个数

# 登录某节点 -h(节点host)、 -p (节点port)、-c(集群模式)
redis-cli -h 127.0.0.1 -p 6380 -c

# 查看主从节点信息

cluster nodes

# 查看集群信息

cluster info

4、SpringBoot整合redis集群

pom依赖

<?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.4</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>redis-cluster-demo</artifactId>
    <version>0.0.1</version>
    <name>redis-cluster-demo</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>


        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>io.lettuce</groupId>
                    <artifactId>lettuce-core</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>2.0.28</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>


                <configuration>
                    <!-- 没有该配置,devtools 不生效 -->
                    <!--                    <fork>true</fork>-->
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

(1)方法一简单粗暴

package com.example.redisclusterdemo.other;

import com.alibaba.fastjson.JSON;
import com.example.redisclusterdemo.common.Person;
import org.apache.catalina.core.ApplicationContext;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPoolConfig;

import java.util.LinkedHashSet;
import java.util.Set;

/**
 * TODO 类描述 集群测试
 *
 * @author WKQ
 * @date 2023/10/23
 */

public class Test {
    public static void main(String[] args) throws Exception {
        testRedisCluster () ;
    }

    /**
     * 连接 redisCluster(集群模式)
     */
    static JedisCluster cluster ;
    public static void testRedisCluster() {
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        // 最大连接数
        poolConfig.setMaxTotal(1000);
        // 最大空闲数
        poolConfig.setMaxIdle(1000);
        // 最大允许等待时间,如果超过这个时间还未获取到连接,则会报JedisException异常:
        // Could not get a resource from the pool
        poolConfig.setMaxWaitMillis(3000);
        poolConfig.setTestOnBorrow(true);
        Set<HostAndPort> nodes = new LinkedHashSet<HostAndPort>();
        //换自己的内网IP
        nodes.add(new HostAndPort("127.0.0.1" ,6380 ));
        nodes.add(new HostAndPort("127.0.0.1" ,6381 ));
        nodes.add(new HostAndPort("127.0.0.1" ,6382 ));
        nodes.add(new HostAndPort("127.0.0.1" ,6383 ));
        nodes.add(new HostAndPort("127.0.0.1" ,6384 ));
        nodes.add(new HostAndPort("127.0.0.1" ,6385 ));
        cluster = new JedisCluster( nodes, 3000, 3000, 8, poolConfig );
        cluster.set("name", "小扑街");
        String name = cluster.get("name");
        System.out.println(name);

//        cluster.set("dog", JSON.toJSONString(new Person("小扑街",28)));
//        System.out.println(cluster.get("dog"));

    }
}


(2)根据方法一优化,配置相关bean进行redis操作

package com.example.redisclusterdemo.config;

import org.apache.catalina.core.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPoolConfig;

import java.util.LinkedHashSet;
import java.util.Set;

/**
 * TODO 类描述
 *
 * @author WKQ
 * @date 2023/10/23
 */
@Component
public class RedisClusterConfig {

    @Bean
    public JedisCluster testRedisCluster() {
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        // 最大连接数
        poolConfig.setMaxTotal(1000);
        // 最大空闲数
        poolConfig.setMaxIdle(300);
        // 最大允许等待时间,如果超过这个时间还未获取到连接,则会报JedisException异常:
        // Could not get a resource from the pool
        poolConfig.setMaxWaitMillis(3000);
        poolConfig.setTestOnBorrow(true);
        Set<HostAndPort> nodes = new LinkedHashSet<HostAndPort>();
        nodes.add(new HostAndPort("127.0.0.1" ,6380 ));
        nodes.add(new HostAndPort("127.0.0.1" ,6381 ));
        nodes.add(new HostAndPort("127.0.0.1" ,6382 ));
        nodes.add(new HostAndPort("127.0.0.1" ,6383 ));
        nodes.add(new HostAndPort("127.0.0.1" ,6384 ));
        nodes.add(new HostAndPort("127.0.0.1" ,6385 ));

        return new JedisCluster( nodes, 3000, 3000, 8, poolConfig );


    }
}

怎么使用这个bean就不用我教了,方法一里面有,往前翻

(3)正常开发情况下使用

正常开发情况,节点配置会在yaml中配置,JedisCluster的bean也是在配置类中配置

server:
  port: 8787
  servlet:
    context-path: /cluster
spring:
#  data:
  redis:
    database: 0
    cluster:
      nodes:
        - 127.0.0.1:6380
        - 127.0.0.1:6381
        - 127.0.0.1:6382
        - 127.0.0.1:6383
        - 127.0.0.1:6384
        - 127.0.0.1:6385
      # 最大尝试次数
      maxAttempts: 3
    jedis:
      pool:
        # 连接池最大连接数
        max-active: 1000
        # 连接池中的最大空闲连接
        max-idle: 100
        # 连接池资源用尽后,调用者的最大等待时间(单位为毫秒),默认值为-1,表示永远不超时,一直等待
        max-wait: -1
        # 连接池中的最小空闲连接
        min-idle: 5
    timeout: 6000


读取reids cluster配置


import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.List;

/**
 * TODO 类描述
 *  读取yaml文件redis集群节点配置
 * @author WKQ
 * @date 2023/10/27
 */
@Data
@Component
@ConfigurationProperties(prefix = "spring.redis.cluster")
public class RedisClusterConfig {
    /**
     * 集群节点
     */
    private List<String> nodes;


    /**
     * 最大尝试次数
     */
    private Integer maxAttempts;


}

读取jedis配置



import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.HashMap;

/**
 * TODO 类描述
 *
 * @author WKQ
 * @date 2023/10/27
 */
@Data
@Component
@ConfigurationProperties(prefix = "spring.redis.jedis")
public class JedisConfig {
    private HashMap<String,Integer> pool;
}

配置JedisCluster操作bean


import com.example.redisclusterdemo.common.JedisConfig;
import com.example.redisclusterdemo.common.RedisClusterConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.CollectionUtils;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPoolConfig;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * TODO 类描述
 *      配置JedisCluster操作bean
 * @author WKQ
 * @date 2023/10/23
 */
@Slf4j
@Configuration
public class RedisConfigCluster extends CachingConfigurerSupport {
    /**
     * 连接超时时间
     */
    @Value("${spring.redis.timeout}")
    private Integer timeout;
    @Resource
    JedisConfig jedisConfig;
    @Resource
    RedisClusterConfig redisClusterConfig;


    /**
     * JedisPoolConfig jedis配置
     * @return JedisPoolConfig
     */
    @Bean
    public JedisPoolConfig jedisPoolConfig() {
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        // 连接池最大连接数
        jedisPoolConfig.setMaxTotal(jedisConfig.getPool().get("max-active"));
        // 连接池中的最大空闲连接
        jedisPoolConfig.setMaxIdle(jedisConfig.getPool().get("max-idle"));
        // 连接池中的最小空闲连接
        jedisPoolConfig.setMinIdle(jedisConfig.getPool().get("min-idle"));
        return jedisPoolConfig;
    }


    /**
     * 配置JedisCluster操作bean
     * @return JedisCluster
     */
    @Bean
    public JedisCluster jedisCluster() {

        // redis集群节点
        Set<HostAndPort> set = new HashSet<>();
        List<String> nodes = redisClusterConfig.getNodes();

        if (!CollectionUtils.isEmpty(nodes)) {
            for (String node : nodes) {
                System.out.println("node ------------->"+node);
                String[] hostPort = node.split(":");
                if (hostPort.length > 0) {
                    // ip+port
                    set.add(new HostAndPort(hostPort[0], Integer.parseInt(hostPort[1])));
                }
            }
        }

        log.info("================redis cluster初始化");
        // JedisCluster(节点HostAndPort集合、 连接超时时间、读取超时时间、集群最大尝试次数、jedisPool连接池配置类)
        return new JedisCluster(set, timeout, timeout, redisClusterConfig.getMaxAttempts(), jedisPoolConfig());
    }
}

5、gitee地址,有兴趣可以自己拷贝,很简陋

git@gitee.com:ivanWKQ/jedsicluster.git

6、参考

引用:win10下redis5的集群搭建_windows 搭建redis5 集群_森森之火的博客-CSDN博客

引用:   Jedis 连接Redis 集群_jedis连接redis集群_梁踏歌的博客-CSDN博客

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值