关于程序员:jtday15

27次阅读

共计 1802 个字符,预计需要花费 5 分钟才能阅读完成。

1SpringBoot 整合 Redis 集群

1.### 编辑 properties 文件

# 配置单台 redis 服务器
#redis.host=192.168.126.129
#redis.port=6379

## 配置 redis 分片
#redis.nodes=192.168.126.129:6379,192.168.126.129:6380,192.168.126.129:6381

# redis 集群配置
redis.nodes=192.168.126.129:7000,192.168.126.129:7001,192.168.126.129:7002,192.168.126.129:7003,192.168.126.129:7004,192.168.126.129:7005

2. 编辑配置类

package com.jt.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import redis.clients.jedis.*;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Configuration  // 标识我是配置类
@PropertySource("classpath:/properties/redis.properties")
public class RedisConfig {

    // 实现 redis 集群操作
    @Value("${redis.nodes}")
    private String nodes;       //node,node,node

    @Bean
    public JedisCluster jedisCluster(){Set<HostAndPort> nodeSet = new HashSet<>();
        String[] nodeArray = nodes.split(",");
        for (String node : nodeArray){ //host:port
            String host = node.split(":")[0];
            int port = Integer.parseInt(node.split(":")[1]);
            nodeSet.add(new HostAndPort(host,port));
        }
        return new JedisCluster(nodeSet);
    }

    /*@Bean
    public ShardedJedis shardedJedis(){List<JedisShardInfo> shards = new ArrayList<>();
        String[] nodeArray = nodes.split(",");
        for (String node : nodeArray){ //node=ip:port
            String host = node.split(":")[0];
            int port = Integer.parseInt(node.split(":")[1]);
            // 筹备分片节点信息
            JedisShardInfo info  = new JedisShardInfo(host, port);
            shards.add(info);
        }
        return new ShardedJedis(shards);
    }*/


   /* @Value("${redis.host}")
    private String  host;
    @Value("${redis.port}")
    private Integer port;

    @Bean
    public Jedis jedis(){return new Jedis(host, port);
    }*/
}

3.### 编辑 AOP 配置

@Aspect
@Component
public class CacheAop {
    @Autowired
 private JedisCluster jedis;
//    private ShardedJedis jedis;// 配置类中定义的类型
//    private Jedis jedis;

4. 成果展现

正文完
 0