redis-cluster做spring-boot的缓存

    网上有很多redis做spring-boot缓存的例子,贴两篇写的比较详细的。

    https://www.jianshu.com/p/5a70b13a4fa7

    https://blog.csdn.net/canot/article/details/52702029

    但关于redis-cluster做spring-boot缓存的例子真是少之又少,所以就写这篇文章记录下过程。如果有还没看过redis做缓存文章的同学请先阅读上两篇文章,再阅读本文。

一.连接Redis-cluster的方式

    有两种,一种是jedis连接,一种是Spring-data-redis,pom中的引用如下。

        <dependency>  
            <groupId>org.springframework.data</groupId>
	    <artifactId>spring-data-redis</artifactId>
       	</dependency> 
       	<dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
        </dependency>

    jedis连接redis集群非常简单,也可直接操作jedisCluster来增删改查数据库。但有个问题是,要用redisCacheManager做为springboot的cachemanager,需要RedisTemplate参数,目前本人没找到怎么通过JedisCluster获取到redisTemplate,毕竟连包都不一样。

@Bean
public JedisCluster getJedisCluster() {
		// 创建set集合
		Set<HostAndPort> nodes = new HashSet<HostAndPort>();
		// 循环数组把集群节点添加到set集合中
		for (String node : clusterNodes) {
			String[] host = node.split(":");
			// 添加集群节点
			nodes.add(new HostAndPort(host[0], Integer.parseInt(host[1])));
		}
		JedisCluster jc = new JedisCluster(nodes);
		return jc;
}
        另一种spring-data-redis,连接集群相对较复杂,要按照RedisClusterConfiguration -> JedisConnectionFactory -> RedisTemplate 的顺序来获得redisTemplate,但好处就是可以跟new RedisCacheManage(redisTemplate)联系上了。

二. redis 保存类型

    service中的配置很基本,大致如下

        // 如果方法没有参数,则使用SimpleKey[]作为key
	@Cacheable(value="people")
	public List<UserEntity> list(String name){
		return jpa.findAll();
	}

    那么执行了这个方法后,redis里保存的是什么类型的数据呢?我们用redis可视化工具查看,会发现生成了一个名为"people~keys"的zset类型key,里面保存的是字符串,同时又对应了另外的String类型的key


    

三.结尾

    源码自取,很多地方需要自己手动打断点看看才会有个更全面的认知,大家共勉!

猜你喜欢

转载自blog.csdn.net/qq_30905661/article/details/80859407