场景

大批量提交数据到redis集群服务器中,如直接使用redisTemplate 就会报如下错误:

Pipeline is currently not supported for JedisClusterConnection

原因是:Jedis中JedisCluster是不支持pipeline ,spring-boot-starter-data-Redis用到了pipeline

在org.springframework.data.redis.connection.jedis.JedisClusterConnection.java

openPipeline()方法返回的报错

阅读别人的资料说明了哈希槽(hash slot)

redis cluster一共有16384个桶,用来存储数据,建立集群的时候会返回这样的信息,如下图

springboot代码配置redis数据源(SpringBoot-Data中对rediscluster集群使用pipeline)(1)

数据set时,会用CRC16算法算出一个值,这个值就是对应redisu cluster 的hash slot ,就可以知道这个key存放到那个节点上了

别人的代码,其中我修改了一点,否则是报错的,红色字体

RedisConnectionFactory factory = redisTemplate.getConnectionFactory(); RedisConnection redisConnection = factory.getConnection(); JedisClusterConnection jedisClusterConnection = (JedisClusterConnection) redisConnection; JedisCluster jedisCluster = jedisClusterConnection.getNativeConnection(); int slot = JedisClusterCRC16.getSlot(key); Field field = BinaryJedisCluster.class.getDeclaredField("connectionHandler"); field.setAccessible(true); JedisSlotBasedConnectionHandler jedisClusterConnectionHandler = (JedisSlotBasedConnectionHandler) field.get(jedisCluster); Jedis jedis = jedisClusterConnectionHandler.getConnectionFromSlot(slot); Pipeline pipeline = jedis.pipelined(); ... pipeline.syncAndReturnAll(); jedis.close(); RedisConnectionUtils.releaseConnection(redisConnection, factory);

,