资讯 小学 初中 高中 语言 会计职称 学历提升 法考 计算机考试 医护考试 建工考试 教育百科
栏目分类:
子分类:
返回
空麓网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
空麓网 > 计算机考试 > 软件开发 > 后端开发 > Java

11.Redis分布式、分片式集群基本使用

Java 更新时间: 发布时间: 计算机考试归档 最新发布

11.Redis分布式、分片式集群基本使用

目录


什么是缓存?为什么要使用缓存?

1. Redis基本介绍(NoSQL)

2. Redis下载安装配置(Windows、Linux、Ubuntu)、Redis-cli(客户端)基本命令、Redis可视化工具(Redis Desktop Manager)

3. Redis数据类型及其操作命令

4. Redis安全(创建用户)、数据备份与恢复、管道技术、分区

5. Redis HyperLogLog、发布订阅、事务、脚本、服务器命令

6. 基本使用Redis(key-value,键值对)

7. 传统Spring中使用Redis

8. Spring Boot中使用Redis

9. Redis主从复制(Master/Slave)

10. Reids哨兵模式

11. Redis分布式、分片式集群基本使用


Redis分布式、分片式集群基本使用

  • 目录
  • Redis分布式、分片式集群基本使用
    • 客户端集群(分片式)
      • 1.redis.properties配置文件
      • 2.配置applicationContext-redis.xml
      • 3.封装ShardedJedisPool使用
      • 分片式集群使用:需要两台电脑
    • 服务端集群(分布式)
      • 1.导入依赖
      • 2.redis.properties配置文件
      • 3.配置文件(applicationContext.xml)
      • 4.Service自动注入RedisService使用
    • Spring Boot使用Redis集群

Redis分布式、分片式集群基本使用

提高Redis的读写能力

客户端集群(分片式)

1.redis.properties配置文件

redis.maxTotal=200redis.node1.ip=127.0.0.1redis.node1.port=6379redis.node2.ip=localhostredis.node2.port=6379

2.配置applicationContext-redis.xml

																													

3.封装ShardedJedisPool使用

@Servicepublic class RedisService {	// 注入的分片集群的连接池	@Autowired(required = false)	private ShardedJedisPool shardedJedisPool;	// 抽取一个方法	public  T execute(RedisFunction fun) {		ShardedJedis jedis = null;		try {			jedis = shardedJedisPool.getResource();			return fun.callback(jedis);// 执行具体的方法,具体的方法知道吗?		} finally {			if (null != jedis) {				// 关闭资源,把连接放回我们的连接池中				jedis.close();			}		}	}		public String set(String key, String value) {		return execute(new RedisFunction() {			@Override			public String callback(ShardedJedis e) {				return e.set(key, value);			}		});	}		public String set(String key, String value, Integer seconds) {		return execute(new RedisFunction() {			@Override			public String callback(ShardedJedis e) {				String str = e.set(key, value);				e.expire(key, seconds);				return str;			}		});	}		public String get(String key) {		return execute(new RedisFunction() {			@Override			public String callback(ShardedJedis e) {				return e.get(key);			}		});	}		public Long del(String key) {		return execute(new RedisFunction() {			@Override			public Long callback(ShardedJedis e) {				return e.del(key);			}		});	}		public Long expire(String key, Integer seconds) {		return execute(new RedisFunction() {			@Override			public Long callback(ShardedJedis e) {				return e.expire(key, seconds);			}		});	}}

分片式集群
在redis中的集群有两种
(1)一种是分片式集群
(2)一种是官方正式提出的集群

无法动态增加减少服务节点
ps: redis在3.0之前是没有集群的

为什么无法动态增加减少服务节点?
因为服务节点的数量,涉及到了hash值的计算,如果现在有两台服务器,hash值是要根据这两台服务器去查找;如果有三台,那么hash值的计算就会发生变化,;同理如果4台,5台同样也会发生变化,减少服务器节点也是一样的

那么分片就不用了?
当然不是,如果架构中存在两台redis服务器,足以支撑服务,就不会遇到上面说的问题

早期的时候就只有分片

分片式集群使用:需要两台电脑

// 1.构建一个连接池的信息JedisPoolConfig config = new JedisPoolConfig();// 2.设置最大的连接数config.setMaxTotal(30);// 定义集群信息List list = new ArrayList();list.add(new JedisShardInfo("127.0.0.1", 6379));list.add(new JedisShardInfo("localhost", 6379));// 定义集群连接池ShardedJedisPool pool = new ShardedJedisPool(config, list);// 定于jedis分片对象ShardedJedis shardedJedis = null;// 从连接池中获取jedis分片对象shardedJedis = pool.getResource();// 设置多个数据,通过从连接池中获取的Jedis分片对象设置10个keyfor (int x = 0; x < 10; x++) {	shardedJedis.set("key_" + x, "value_" + x);}// 随便从10个key中获取数据System.out.println(shardedJedis.get("key_0"));System.out.println(shardedJedis.get("key_3"));// 把连接放入到连接池中if (null != shardedJedis) {	// 关闭	shardedJedis.close();}// 关闭连接池pool.close();

服务端集群(分布式)

1.导入依赖

   redis.clients   jedis   2.9.0

2.redis.properties配置文件

redis.maxActive=1000redis.maxIdle=10redis.maxWaitMillis=30000redis.testOnBorrow=true

3.配置文件(applicationContext.xml)

                        classpath:redis.properties                                                                                                                                                                                                

4.Service自动注入RedisService使用

package ink.nzh.infinite.common.redis.service;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.data.redis.core.BoundSetOperations;import org.springframework.data.redis.core.HashOperations;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.data.redis.core.ValueOperations;import org.springframework.stereotype.Component;import java.util.*;import java.util.concurrent.TimeUnit;@Component@SuppressWarnings(value = {"unchecked", "rawtypes"})public class RedisService {    @Autowired    private RedisTemplate redisTemplate;        public  void setCacheObject(final String key, final T value) {        redisTemplate.opsForValue().set(key, value);    }        public  void setCacheObject(final String key, final T value, final Long timeout, final TimeUnit timeUnit) {        redisTemplate.opsForValue().set(key, value, timeout, timeUnit);    }        public boolean expire(final String key, final long timeout) {        return expire(key, timeout, TimeUnit.SECONDS);    }        public boolean expire(final String key, final long timeout, final TimeUnit unit) {        return redisTemplate.expire(key, timeout, unit);    }        public long getExpire(final String key) {        return redisTemplate.getExpire(key);    }        public Boolean hasKey(String key) {        return redisTemplate.hasKey(key);    }        public  T getCacheObject(final String key) {        ValueOperations operation = redisTemplate.opsForValue();        return operation.get(key);    }        public boolean deleteObject(final String key) {        return redisTemplate.delete(key);    }        public long deleteObject(final Collection collection) {        return redisTemplate.delete(collection);    }        public  long setCacheList(final String key, final List dataList) {        Long count = redisTemplate.opsForList().rightPushAll(key, dataList);        return count == null ? 0 : count;    }        public  List getCacheList(final String key) {        return redisTemplate.opsForList().range(key, 0, -1);    }        public  BoundSetOperations setCacheSet(final String key, final Set dataSet) {        BoundSetOperations setOperation = redisTemplate.boundSetOps(key);        for (T t : dataSet) {            setOperation.add(t);        }        return setOperation;    }        public  Set getCacheSet(final String key) {        return redisTemplate.opsForSet().members(key);    }        public  void deleteMap(final String key, final String hashKey) {        redisTemplate.opsForHash().delete(key, hashKey);    }        public  void setCacheMap(final String key, final Map dataMap) {        if (dataMap != null) {            redisTemplate.opsForHash().putAll(key, dataMap);        }    }        public  Map getCacheMap(final String key) {        return redisTemplate.opsForHash().entries(key);    }    public Long getCacheMapSize(final String key) {        return redisTemplate.opsForHash().size(key);    }        public  void setCacheMapValue(final String key, final String hKey, final T value) {        redisTemplate.opsForHash().put(key, hKey, value);    }        public  T getCacheMapValue(final String key, final String hKey) {        HashOperations opsForHash = redisTemplate.opsForHash();        return opsForHash.get(key, hKey);    }        public  List getMultiCacheMapValue(final String key, final Collection hKeys) {        return redisTemplate.opsForHash().multiGet(key, hKeys);    }        public Collection keys(final String pattern) {        return redisTemplate.keys(pattern);    }} 

Spring Boot使用Redis集群

redis cluster集群在以下情况下判断集群宕机:
a.当超过半数的主节点宕机
b.某个主节点和下面的从节点全部宕机

spring.redis.database=0spring.redis.jedis.pool.max-active=8spring.redis.jedis.pool.max-wait=-1spring.redis.jedis.pool.max-idle=8spring.redis.jedis.pool.min-idle=0spring.redis.timeout=10000spring.redis.cluster.nodes=127.0.0.1:8001,127.0.0.1:8002,127.0.0.1:8003,127.0.0.1:8004, 127.0.0.1:8005, 127.0.0.1:8006

Service自动注入RedisService使用

package ink.nzh.infinite.common.redis.service;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.data.redis.core.BoundSetOperations;import org.springframework.data.redis.core.HashOperations;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.data.redis.core.ValueOperations;import org.springframework.stereotype.Component;import java.util.*;import java.util.concurrent.TimeUnit;@Component@SuppressWarnings(value = {"unchecked", "rawtypes"})public class RedisService {    @Autowired    private RedisTemplate redisTemplate;        public  void setCacheObject(final String key, final T value) {        redisTemplate.opsForValue().set(key, value);    }        public  void setCacheObject(final String key, final T value, final Long timeout, final TimeUnit timeUnit) {        redisTemplate.opsForValue().set(key, value, timeout, timeUnit);    }        public boolean expire(final String key, final long timeout) {        return expire(key, timeout, TimeUnit.SECONDS);    }        public boolean expire(final String key, final long timeout, final TimeUnit unit) {        return redisTemplate.expire(key, timeout, unit);    }        public long getExpire(final String key) {        return redisTemplate.getExpire(key);    }        public Boolean hasKey(String key) {        return redisTemplate.hasKey(key);    }        public  T getCacheObject(final String key) {        ValueOperations operation = redisTemplate.opsForValue();        return operation.get(key);    }        public boolean deleteObject(final String key) {        return redisTemplate.delete(key);    }        public long deleteObject(final Collection collection) {        return redisTemplate.delete(collection);    }        public  long setCacheList(final String key, final List dataList) {        Long count = redisTemplate.opsForList().rightPushAll(key, dataList);        return count == null ? 0 : count;    }        public  List getCacheList(final String key) {        return redisTemplate.opsForList().range(key, 0, -1);    }        public  BoundSetOperations setCacheSet(final String key, final Set dataSet) {        BoundSetOperations setOperation = redisTemplate.boundSetOps(key);        for (T t : dataSet) {            setOperation.add(t);        }        return setOperation;    }        public  Set getCacheSet(final String key) {        return redisTemplate.opsForSet().members(key);    }        public  void deleteMap(final String key, final String hashKey) {        redisTemplate.opsForHash().delete(key, hashKey);    }        public  void setCacheMap(final String key, final Map dataMap) {        if (dataMap != null) {            redisTemplate.opsForHash().putAll(key, dataMap);        }    }        public  Map getCacheMap(final String key) {        return redisTemplate.opsForHash().entries(key);    }    public Long getCacheMapSize(final String key) {        return redisTemplate.opsForHash().size(key);    }        public  void setCacheMapValue(final String key, final String hKey, final T value) {        redisTemplate.opsForHash().put(key, hKey, value);    }        public  T getCacheMapValue(final String key, final String hKey) {        HashOperations opsForHash = redisTemplate.opsForHash();        return opsForHash.get(key, hKey);    }        public  List getMultiCacheMapValue(final String key, final Collection hKeys) {        return redisTemplate.opsForHash().multiGet(key, hKeys);    }        public Collection keys(final String pattern) {        return redisTemplate.keys(pattern);    }}
 
转载请注明:文章转载自 http://www.konglu.com/
免责声明:

我们致力于保护作者版权,注重分享,被刊用文章【11.Redis分布式、分片式集群基本使用】因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理,本文部分文字与图片资源来自于网络,转载此文是出于传递更多信息之目的,若有来源标注错误或侵犯了您的合法权益,请立即通知我们,情况属实,我们会第一时间予以删除,并同时向您表示歉意,谢谢!

我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2023 成都空麓科技有限公司

ICP备案号:蜀ICP备2023000828号-2