服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - Redis6搭建集群并在SpringBoot中使用RedisTemplate的实现

Redis6搭建集群并在SpringBoot中使用RedisTemplate的实现

2022-11-27 15:41玩代码 Java教程

本文主要介绍了Redis6搭建集群并在SpringBoot中使用RedisTemplate,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

原理

Redis Cluster 一般由多个节点组成,节点数量至少为 6 个才能保证组成完整高可用的集群,其中三个为主节点,三个为从节点。三个主节点会分配槽,处理客户端的命令请求,而从节点可用在主节点故障后,顶替主节点。

Redis6搭建集群并在SpringBoot中使用RedisTemplate的实现

如上图所示,该集群中包含6个Redis节点3个主服务器3个从服务器,分别为M1,M2,M3,S1,S2,S3。除了主从 Redis 节点之间进行数据复制外,所有 Redis 节点之间采用 Gossip 协议进行通信,交换维护节点元数据信息。一般来说,主Redis节点会处理Clients的读写操作,而从节点只处理读操作。

 

搭建集群

1.进入redis目录中,打开redis.conf文件,注释掉bind 127.0.0.1,bind自己服务器的IP。并将protected -mode yes改为no。daemonize 默认是no,需要改成yes,以守护进程运行。

Redis6搭建集群并在SpringBoot中使用RedisTemplate的实现

 

Redis6搭建集群并在SpringBoot中使用RedisTemplate的实现

2.分别创建6个conf文件对应不同的端口号,正常每个节点对应一台服务器,为了方便测试本次使用一台服务来搭建集群模式。

redis6379.conf

include redis.conf
pidfile /var/run/redis_6379.pid
port 6379
dbfilename dump6379.rdb
cluster-enabled yes
cluster-node-timeout 15000
cluster-config-file nodes-6379.conf 

redis6380.conf

include redis.conf
pidfile /var/run/redis_6380.pid
port 6380
dbfilename dump6380.rdb
cluster-enabled yes
cluster-node-timeout 15000
cluster-config-file nodes-6380.conf

redis6381.conf

include redis.conf
pidfile /var/run/redis_6381.pid
port 6381
dbfilename dump6381.rdb
cluster-enabled yes
cluster-node-timeout 15000
cluster-config-file nodes-6381.conf 

redis6389.conf

include redis.conf
pidfile /var/run/redis_6389.pid
port 6389
dbfilename dump6389.rdb
cluster-enabled yes
cluster-node-timeout 15000
cluster-config-file nodes-6389.conf 

redis6390.conf

include redis.conf
pidfile /var/run/redis_6390.pid
port 6390
dbfilename dump6390.rdb
cluster-enabled yes
cluster-node-timeout 15000
cluster-config-file nodes-6390.conf 

redis6391.conf

include redis.conf
pidfile /var/run/redis_6391.pid
port 6391
dbfilename dump6391.rdb
cluster-enabled yes
cluster-node-timeout 15000
cluster-config-file nodes-6391.conf 

3.进入到redis安装目录启动redis服务(如之前有nodes、rdb、aof文件请先删除,非则可能会报错)。

Redis6搭建集群并在SpringBoot中使用RedisTemplate的实现

Redis6搭建集群并在SpringBoot中使用RedisTemplate的实现

4.进入src目录中执行如下命令搭建集群。

redis-cli --cluster create --cluster-replicas 1 IP:6379 IP:6380 IP:6381 IP:6389 IP:6390 IP:6391

5.进入其中任意一个节点,执行命令查看当前节点状态

redis-cli - h ip -p 端口info replication

Redis6搭建集群并在SpringBoot中使用RedisTemplate的实现

 

SpringBoot中使用RedisTemplate

1.pom文件中加入依赖。

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

2.创建redis配置类.

package com.wzy.demo.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig {

  @Autowired
  private RedisTemplate redisTemplate;

  /**
   * 解决redis插入中文乱码
   * @return
   */
  @Bean
  public RedisTemplate redisTemplateInit() {
      //设置序列化Key的实例化对象
      redisTemplate.setKeySerializer(new StringRedisSerializer());
      //设置序列化Value的实例化对象
      redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
      return redisTemplate;
  }

}

3.创建RedisUtil工具类

package com.wzy.demo.util;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import javax.annotation.Resource;

@Component
public class RedisUtil {
  @Resource
  private RedisTemplate<String, Object> redisTemplate;

  public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
      this.redisTemplate = redisTemplate;
  }
  //=============================common============================

  /**
   * 指定缓存失效时间
   *
   * @param key  键
   * @param time 时间(秒)
   * @return
   */
  public boolean expire(String key, long time) {
      try {
          if (time > 0) {
              redisTemplate.expire(key, time, TimeUnit.SECONDS);
          }
          return true;
      } catch (Exception e) {
          e.printStackTrace();
          return false;
      }
  }

  /**
   * 根据key 获取过期时间
   *
   * @param key 键 不能为null
   * @return 时间(秒) 返回0代表为永久有效
   */
  public long getExpire(String key) {
      return redisTemplate.getExpire(key, TimeUnit.SECONDS);
  }

  /**
   * 判断key是否存在
   *
   * @param key 键
   * @return true 存在 false不存在
   */
  public boolean hasKey(String key) {
      try {
          return redisTemplate.hasKey(key);
      } catch (Exception e) {
          e.printStackTrace();
          return false;
      }
  }

  /**
   * 删除缓存
   *
   * @param key 可以传一个值 或多个
   */
  @SuppressWarnings("unchecked")
  public void del(String... key) {
      if (key != null && key.length > 0) {
          if (key.length == 1) {
              redisTemplate.delete(key[0]);
          } else {
              redisTemplate.delete(CollectionUtils.arrayToList(key));
          }
      }
  }

  //============================String=============================

  /**
   * 普通缓存获取
   *
   * @param key 键
   * @return 值
   */
  public Object get(String key) {
      return key == null ? null : redisTemplate.opsForValue().get(key);
  }

  /**
   * 普通缓存放入
   *
   * @param key   键
   * @param value 值
   * @return true成功 false失败
   */
  public boolean set(String key, Object value) {
      try {
          redisTemplate.opsForValue().set(key, value);
          return true;
      } catch (Exception e) {
          e.printStackTrace();
          return false;
      }

  }

  /**
   * 普通缓存放入并设置时间
   *
   * @param key   键
   * @param value 值
   * @param time  时间(秒) time要大于0 如果time小于等于0 将设置无限期
   * @return true成功 false 失败
   */
  public boolean set(String key, Object value, long time) {
      try {
          if (time > 0) {
              redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
          } else {
              set(key, value);
          }
          return true;
      } catch (Exception e) {
          e.printStackTrace();
          return false;
      }
  }

  /**
   * 递增
   *
   * @param key 键
   * @param delta  要增加几(大于0)
   * @return
   */
  public long incr(String key, long delta) {
      if (delta < 0) {
          throw new RuntimeException("递增因子必须大于0");
      }
      return redisTemplate.opsForValue().increment(key, delta);
  }

  /**
   * 递减
   *
   * @param key 键
   * @param delta  要减少几(小于0)
   * @return
   */
  public long decr(String key, long delta) {
      if (delta < 0) {
          throw new RuntimeException("递减因子必须大于0");
      }
      return redisTemplate.opsForValue().increment(key, -delta);
  }

  //================================Map=================================

  /**
   * HashGet
   *
   * @param key  键 不能为null
   * @param item 项 不能为null
   * @return 值
   */
  public Object hget(String key, String item) {
      return redisTemplate.opsForHash().get(key, item);
  }

  /**
   * 获取hashKey对应的所有键值
   *
   * @param key 键
   * @return 对应的多个键值
   */
  public Map<Object, Object> hmget(String key) {
      return redisTemplate.opsForHash().entries(key);
  }

  /**
   * HashSet
   *
   * @param key 键
   * @param map 对应多个键值
   * @return true 成功 false 失败
   */
  public boolean hmset(String key, Map<String, Object> map) {
      try {
          redisTemplate.opsForHash().putAll(key, map);
          return true;
      } catch (Exception e) {
          e.printStackTrace();
          return false;
      }
  }

  /**
   * HashSet 并设置时间
   *
   * @param key  键
   * @param map  对应多个键值
   * @param time 时间(秒)
   * @return true成功 false失败
   */
  public boolean hmset(String key, Map<String, Object> map, long time) {
      try {
          redisTemplate.opsForHash().putAll(key, map);
          if (time > 0) {
              expire(key, time);
          }
          return true;
      } catch (Exception e) {
          e.printStackTrace();
          return false;
      }
  }

  /**
   * 向一张hash表中放入数据,如果不存在将创建
   *
   * @param key   键
   * @param item  项
   * @param value 值
   * @return true 成功 false失败
   */
  public boolean hset(String key, String item, Object value) {
      try {
          redisTemplate.opsForHash().put(key, item, value);
          return true;
      } catch (Exception e) {
          e.printStackTrace();
          return false;
      }
  }

  /**
   * 向一张hash表中放入数据,如果不存在将创建
   *
   * @param key   键
   * @param item  项
   * @param value 值
   * @param time  时间(秒)  注意:如果已存在的hash表有时间,这里将会替换原有的时间
   * @return true 成功 false失败
   */
  public boolean hset(String key, String item, Object value, long time) {
      try {
          redisTemplate.opsForHash().put(key, item, value);
          if (time > 0) {
              expire(key, time);
          }
          return true;
      } catch (Exception e) {
          e.printStackTrace();
          return false;
      }
  }

  /**
   * 删除hash表中的值
   *
   * @param key  键 不能为null
   * @param item 项 可以使多个 不能为null
   */
  public void hdel(String key, Object... item) {
      redisTemplate.opsForHash().delete(key, item);
  }

  /**
   * 判断hash表中是否有该项的值
   *
   * @param key  键 不能为null
   * @param item 项 不能为null
   * @return true 存在 false不存在
   */
  public boolean hHasKey(String key, String item) {
      return redisTemplate.opsForHash().hasKey(key, item);
  }

  /**
   * hash递增 如果不存在,就会创建一个 并把新增后的值返回
   *
   * @param key  键
   * @param item 项
   * @param by   要增加几(大于0)
   * @return
   */
  public double hincr(String key, String item, double by) {
      return redisTemplate.opsForHash().increment(key, item, by);
  }

  /**
   * hash递减
   *
   * @param key  键
   * @param item 项
   * @param by   要减少记(小于0)
   * @return
   */
  public double hdecr(String key, String item, double by) {
      return redisTemplate.opsForHash().increment(key, item, -by);
  }

  //============================set=============================

  /**
   * 根据key获取Set中的所有值
   *
   * @param key 键
   * @return
   */
  public Set<Object> sGet(String key) {
      try {
          return redisTemplate.opsForSet().members(key);
      } catch (Exception e) {
          e.printStackTrace();
          return null;
      }
  }

  /**
   * 根据value从一个set中查询,是否存在
   *
   * @param key   键
   * @param value 值
   * @return true 存在 false不存在
   */
  public boolean sHasKey(String key, Object value) {
      try {
          return redisTemplate.opsForSet().isMember(key, value);
      } catch (Exception e) {
          e.printStackTrace();
          return false;
      }
  }

  /**
   * 将数据放入set缓存
   *
   * @param key    键
   * @param values 值 可以是多个
   * @return 成功个数
   */
  public long sSet(String key, Object... values) {
      try {
          return redisTemplate.opsForSet().add(key, values);
      } catch (Exception e) {
          e.printStackTrace();
          return 0;
      }
  }

  /**
   * 将set数据放入缓存
   *
   * @param key    键
   * @param time   时间(秒)
   * @param values 值 可以是多个
   * @return 成功个数
   */
  public long sSetAndTime(String key, long time, Object... values) {
      try {
          Long count = redisTemplate.opsForSet().add(key, values);
          if (time > 0) expire(key, time);
          return count;
      } catch (Exception e) {
          e.printStackTrace();
          return 0;
      }
  }

  /**
   * 获取set缓存的长度
   *
   * @param key 键
   * @return
   */
  public long sGetSetSize(String key) {
      try {
          return redisTemplate.opsForSet().size(key);
      } catch (Exception e) {
          e.printStackTrace();
          return 0;
      }
  }

  /**
   * 移除值为value的
   *
   * @param key    键
   * @param values 值 可以是多个
   * @return 移除的个数
   */
  public long setRemove(String key, Object... values) {
      try {
          Long count = redisTemplate.opsForSet().remove(key, values);
          return count;
      } catch (Exception e) {
          e.printStackTrace();
          return 0;
      }
  }
  //===============================list=================================

  /**
   * 获取list缓存的内容
   *
   * @param key   键
   * @param start 开始
   * @param end   结束  0 到 -1代表所有值
   * @return
   */
  public List<Object> lGet(String key, long start, long end) {
      try {
          return redisTemplate.opsForList().range(key, start, end);
      } catch (Exception e) {
          e.printStackTrace();
          return null;
      }
  }

  /**
   * 获取list缓存的长度
   *
   * @param key 键
   * @return
   */
  public long lGetListSize(String key) {
      try {
          return redisTemplate.opsForList().size(key);
      } catch (Exception e) {
          e.printStackTrace();
          return 0;
      }
  }

  /**
   * 通过索引 获取list中的值
   *
   * @param key   键
   * @param index 索引  index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推
   * @return
   */
  public Object lGetIndex(String key, long index) {
      try {
          return redisTemplate.opsForList().index(key, index);
      } catch (Exception e) {
          e.printStackTrace();
          return null;
      }
  }

  /**
   * 将list放入缓存
   *
   * @param key   键
   * @param value 值
   * @return
   */
  public boolean lSet(String key, Object value) {
      try {
          redisTemplate.opsForList().rightPush(key, value);
          return true;
      } catch (Exception e) {
          e.printStackTrace();
          return false;
      }
  }

  /**
   * 将list放入缓存
   *
   * @param key   键
   * @param value 值
   * @param time  时间(秒)
   * @return
   */
  public boolean lSet(String key, Object value, long time) {
      try {
          redisTemplate.opsForList().rightPush(key, value);
          if (time > 0) expire(key, time);
          return true;
      } catch (Exception e) {
          e.printStackTrace();
          return false;
      }
  }

  /**
   * 将list放入缓存
   *
   * @param key   键
   * @param value 值
   * @return
   */
  public boolean lSet(String key, List<Object> value) {
      try {
          redisTemplate.opsForList().rightPushAll(key, value);
          return true;
      } catch (Exception e) {
          e.printStackTrace();
          return false;
      }
  }

  /**
   * 将list放入缓存
   *
   * @param key   键
   * @param value 值
   * @param time  时间(秒)
   * @return
   */
  public boolean lSet(String key, List<Object> value, long time) {
      try {
          redisTemplate.opsForList().rightPushAll(key, value);
          if (time > 0) expire(key, time);
          return true;
      } catch (Exception e) {
          e.printStackTrace();
          return false;
      }
  }

  /**
   * 根据索引修改list中的某条数据
   *
   * @param key   键
   * @param index 索引
   * @param value 值
   * @return
   */
  public boolean lUpdateIndex(String key, long index, Object value) {
      try {
          redisTemplate.opsForList().set(key, index, value);
          return true;
      } catch (Exception e) {
          e.printStackTrace();
          return false;
      }
  }

  /**
   * 移除N个值为value
   *
   * @param key   键
   * @param count 移除多少个
   * @param value 值
   * @return 移除的个数
   */
  public long lRemove(String key, long count, Object value) {
      try {
          Long remove = redisTemplate.opsForList().remove(key, count, value);
          return remove;
      } catch (Exception e) {
          e.printStackTrace();
          return 0;
      }
  }
}

4.在controller中测试redis。

@RequestMapping("/testRedis")
  public String testRedis(Model model) throws Exception{
  redisUtil.set("myid","123456");
  Object object = redisUtil.get("myid");
  model.addAttribute("redisKey",String.valueOf(object));
  return "redis.html";
}

5.页面中显示redis的返回结果。

Redis6搭建集群并在SpringBoot中使用RedisTemplate的实现

到此这篇关于Redis6搭建集群并在SpringBoot中使用RedisTemplate的实现的文章就介绍到这了,更多相关SpringBoot使用RedisTemplate内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/oGuiGui12345/article/details/124425758

延伸 · 阅读

精彩推荐