上一节我们介绍了mariaDB集群的搭建,这一节我们介绍一下redis集群的搭建以及在springboot中使用redis集群。
一、redis集群的搭建
redis集群的搭建我们同样没有使用operator的形式,而是同样手动搭建,基本上是按照下面两篇博文中的步骤来的,在此再次感谢相关的作者:
https://blog.csdn.net/zhutongcloud/article/details/90768390
https://www.jianshu.com/p/a34790c730cf
总结起来的步骤就是下面几步:
第一步:前期准备阶段,跟上一节mariaDB集群一样,使用nfs存储来作为Redis的后端存储,NFS的路径设置为/appl/install(完全可以自行更改);创建StorageClass指定为nfs以便动态创建PVC和PV。
kind: StorageClass
apiVersion: storage.k8s.io/v1
metadata:
name: nfs
provisioner: mynfs
reclaimPolicy: Delete
volumeBindingMode: Immediate
第二步:创建redis专用的namespace以及用到的ConfigMap:
namespace:
kind: Namespace
apiVersion: v1
metadata:
name: demo-redis
ConfigMap:
kind: ConfigMap
apiVersion: v1
metadata:
name: redis-cluster-configmap
namespace: demo-redis
data:
redis.conf: |
appendonly yes
protected-mode no
cluster-enabled yes
cluster-config-file /var/lib/redis/nodes.conf
cluster-node-timeout 5000
dir /var/lib/redis
port 6379
注意:redis有两种持久化存储的格式,一种是AOF一种是RDB,我这里使用的是AOF,因此在redis.conf中添加了“appendonly yes”。
第三步:使用StatefulSet来创建redis的pod(注意:这里没有遵从上面两个链接博文中的先创建pv,pvc然后关联pod,而是直接动态创建pvc和pv):
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: redis-app
namespace: demo-redis
spec:
serviceName: redis-headless-service
replicas: 6
selector:
matchLabels:
app: redis
appCluster: redis-cluster
template:
metadata:
labels:
app: redis
appCluster: redis-cluster
spec:
terminationGracePeriodSeconds: 20
affinity:
podAntiAffinity:
preferredDuringSchedulingIgnoredDuringExecution:
- weight: 100
podAffinityTerm:
labelSelector:
matchExpressions:
- key: app
operator: In
values:
- redis
topologyKey: kubernetes.io/hostname
containers:
- name: redis
image: "redis"
command:
- "redis-server"
args:
- "/etc/redis/redis.conf"
- "--protected-mode"
- "no"
resources:
requests:
cpu: 1000m
memory: 1Gi
limits:
cpu: 1000m
memory: 1Gi
ports:
- name: redis
containerPort: 6379
protocol: "TCP"
- name: cluster
containerPort: 16379
protocol: "TCP"
volumeMounts:
- name: redis-conf
mountPath: /etc/redis
- name: redis-data
mountPath: /var/lib/redis
volumes:
- name: redis-conf
configMap:
name: redis-cluster-configmap
items:
- key: redis.conf
path: redis.conf
volumeClaimTemplates:
- metadata:
name: redis-data
annotations:
volume.beta.kubernetes.io/storage-class: "nfs"
spec:
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 2Gi
注意,我们创建了6个副本,符合我们redis集群3+3的配置。
第四步:创建headless service,同时创建提供与其他微服务或者外网访问的service:
Headless service:
apiVersion: v1
kind: Service
metadata:
name: redis-headless-service-------与上面StatefulSet中的serviceName一致。
namespace: demo-redis
labels:
app: redis
spec:
ports:
- name: redis-port
port: 6379
clusterIP: None
selector:
app: redis
appCluster: redis-cluster
与其他微服务互通的sevice:
apiVersion: v1
kind: Service
metadata:
name: redis-access-service
namespace: demo-redis
labels:
app: redis
spec:
type: NodePort
ports:
- name: redis-port
protocol: TCP
port: 6379
targetPort: 6379
nodePort: 32379
selector:
app: redis
appCluster: redis-cluster
注意:这里如果redis集群不会对外提供服务的话,没有必要使用NodePort这种方式,只分配内网访问的port即可。
完成上面的4步并且执行这些yaml文件之后,我们仅仅是创建并启动了6个redis的pod, 但是它们并没有形成一个集群,下面的第五步才是通过配置将这6个pod构建成一个集群。
第五步:进入当前任何一个redis的pod中开始搭建cluster集群:
1. 进入pod中,执行命令类似于“kubectl exec -it redis-app-2 -n demo-redis /bin/bash”
2. 因为构建的时候需要使用dig命令,由于我们的yaml文件中使用的redis镜像中没有这个命令,需要自行安装,如果你跟我一样使用了公司服务器,访问外网需要代理,那请首先在redis容器(ubuntu系统)中配置代理,修改/etc/apt/apt.conf添加:
Acquire::http::Proxy "xxx";
Acquire::https::Proxy "xxx";
3. 然后执行apt-get update以及apt-get install dnsutils安装dig命令。
4. 在redis5之后的版本中,手动搭建redis集群已经不需要安装redis-trib.rb,已经集成到redis-cli中(如果您安装的redis镜像版本是redis5之前的,那就需要自行安装redis-trib.rb,使用redis-trib命令),因此确保下面的命令正确运行:
redis-cli --cluster create `dig +short redis-app-0.redis-headless-service.demo-redis.svc.cluster.local`:6379 `dig +short redis-app-1.redis-headless-service.demo-redis.svc.cluster.local`:6379 `dig +short redis-app-2.redis-headless-service.demo-redis.svc.cluster.local`:6379 `dig +short redis-app-3.redis-headless-service.demo-redis.svc.cluster.local`:6379 `dig +short redis-app-4.redis-headless-service.demo-redis.svc.cluster.local`:6379 `dig +short redis-app-5.redis-headless-service.demo-redis.svc.cluster.local`:6379 --cluster-replicas 1
注意:类似与`dig +short redis-app-0.redis-headless-service.demo-redis.svc.cluster.local`这种命令指的是动态获得每一个pod的ip地址,因为pod的ip每次重启都是不同的,因此一定不能hardcode,而使用StatefulSet以及headless service能为我们创建的每个pod分配一个固定的dns域名,格式为$podName.$headlessServiceName.$namespace.svc.cluster.local,这样是不是就很好理解了呢?所以整个上面这条命令就是将每个pod的动态ip和端口构建成一个集群,后面的参数“--cluster-replicas 1”代表是一主一从的方式,所以最终就是三主三从。
5. 此时redis集群已经创建成功,为了验证,登陆任何一个pod,执行下面的操作就能看到当前pod的角色以及整个cluster的信息:
/usr/local/bin/redis-cli -c
127.0.0.1:6379> cluster nodes
97a7d4758a3cd17a5a7a88cb0858e049d7116836 10.244.1.236:6379@16379 slave 2cad20ff68341b6fd77b617265922cc9f16ef26d 0 1636509315819 2 connected
3e18ab8e60d3f9189e34268ad68db6f8b9a763d7 10.244.2.219:6379@16379 master - 0 1636509317326 3 connected 10923-16383
fcdd840cc2e621e4ea720b5bf8f50b3b0b3f2e9a 10.244.1.240:6379@16379 myself,slave 3e18ab8e60d3f9189e34268ad68db6f8b9a763d7 0 1636509316000 3 connected
094ad7e577e813abc1596f47e57867f517f2920b 10.244.2.220:6379@16379 slave ee85f7ef9256585308195b494770d76721823702 0 1636509317828 1 connected
ee85f7ef9256585308195b494770d76721823702 10.244.1.235:6379@16379 master - 0 1636509316823 1 connected 0-5460
2cad20ff68341b6fd77b617265922cc9f16ef26d 10.244.1.241:6379@16379 master - 0 1636509316522 2 connected 5461-10922
127.0.0.1:6379> cluster info
cluster_state:ok
cluster_slots_assigned:16384
cluster_slots_ok:16384
cluster_slots_pfail:0
cluster_slots_fail:0
cluster_known_nodes:6
cluster_size:3
cluster_current_epoch:6
cluster_my_epoch:3
cluster_stats_messages_ping_sent:991
cluster_stats_messages_pong_sent:1063
cluster_stats_messages_meet_sent:1
cluster_stats_messages_sent:2055
cluster_stats_messages_ping_received:1063
cluster_stats_messages_pong_received:992
cluster_stats_messages_received:2055
127.0.0.1:6379> role
1) "slave"
2) "10.244.2.219"
3) (integer) 6379
4) "connected"
5) (integer) 840
最后补充一点我们创建的这套redis集群的信息,包括3个master和3个slave,3个master的slot(槽位,redis用0~16383个槽位来存储key)分别为0~5460,5461~10922,10923~16383, 添加key的时候就会通过算法计算后加入对应槽位的master中并且同步到该master对应的slave中。
二、在springboot中访问redis集群
Springboot中访问redis集群也是相当简单,首先在application.properties中配置redis集群的node信息、访问的服务名以及访问端口:
spring.redis.cluster.nodes=redis-app-0.redis-headless-service.demo-redis.svc.cluster.local:6379,redis-app-1.redis-headless-service.demo-redis.svc.cluster.local:6379,redis-app-2.redis-headless-service.demo-redis.svc.cluster.local:6379,redis-app-3.redis-headless-service.demo-redis.svc.cluster.local:6379,redis-app-4.redis-headless-service.demo-redis.svc.cluster.local:6379,redis-app-5.redis-headless-service.demo-redis.svc.cluster.local:6379
spring.redis.host=redis-access-service.demo-redis
spring.redis.port=6379
其次在pom.xml中加入redis的依赖:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
再次,配置redis的全局配置文件RedisConfig.java,其中重写了RedisTemplate的实例方法,方法中定义了redis的key和value的序列化器。
package com.example.demo.configuration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.RedisConnectionFactory; 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 { @Bean public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) { RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(factory); redisTemplate.setKeySerializer(new StringRedisSerializer()); redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer()); redisTemplate.setHashKeySerializer(new StringRedisSerializer()); redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer()); redisTemplate.afterPropertiesSet(); return redisTemplate; } }
再再次,按照处理此类中间件的惯例,我们应该将redis的常用操作封装成一个工具类,此类工具类网上比比皆是,大家自行搜索,我列出我使用的工具类:
RedisClientUtil.java
package com.example.demo.utils; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Component; import org.springframework.util.CollectionUtils; @Component public class RedisClientUtil { @Autowired private RedisTemplate<String, Object> redisTemplate;--------注意这里使用的就是上面重写的实例方法 /** * 指定缓存失效时间 */ 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获取过期时间 */ 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; } } /** * 删除缓存 */ @SuppressWarnings("unchecked") public void del(String... key) { if(key != null && key.length > 0) { if(key.length == 1) { redisTemplate.delete(key[0]); } else { redisTemplate.delete((Collection<String>) CollectionUtils.arrayToList(key)); } } } /** * 普通缓存获取 * * @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; } } }
最后,就是实际的访问调用:
@RequestMapping(value = "/run", method = RequestMethod.POST) public Result Run(@RequestBody String jsonString) { try { String redisKey = UUID.randomUUID().toString().replaceAll("-", ""); JSONObject jsonObject = JSONObject.parseObject(jsonString); String caseName = jsonObject.getString("CaseName"); List<String> logList = new ArrayList<>(); logList.add("Ready to execute the case: "+caseName);
//insert into redis Map<String, Object>mapForRedis = new HashMap<>(); mapForRedis.put("jobID", redisKafkaKey); mapForRedis.put("caseName", caseName); mapForRedis.put("logList", logList); redisClientUtil.hmset(redisKey, mapForRedis); ......
//add redisKey into jsonObject and pass to other micro-service jsonObject.put("redisKey", redisKey ); String passStrToExecute = JSONObject.toJSONString(jsonObject); String executeUrl = "http://execute-service:9000/Execute/runSingleCase"; String resForExecute = OkHttpClientUtil.doPostJson(executeUrl, null, passStrToExecute); if(resForExecute == "") { redisClientUtil.del(redisKafkaKey); return ResultFactory.buildFailResult("Execute-service throw error!"); } return ResultFactory.buildSuccessResult(null); }
而其他微服务如果需要从redis集群中取数据也只需要简单的调用即可:
OK,到此为止,您是否觉得redis集群的搭建和使用很简单呢?其实主要是因为我们的应用场景简单,让我们过滤掉了一下redis集群更强大的功能比如说哨兵模式~~