项目中遇到了MGET获取10000+数据时超时的问题,然后找到网友的测试结果如下(这里就不再重发测试代码,测试结果一致)
结论
解决办法及测试结果(上代码看结果)
package cn.hs; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.redis.core.RedisCallback; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.test.context.junit4.SpringRunner; import javax.annotation.Resource; import java.nio.charset.StandardCharsets; import java.util.HashSet; import java.util.Set; @RunWith(SpringRunner.class) @SpringBootTest public class RedisGetTests { private static final String TYPE_NAME = RedisGetTests.class.getTypeName(); @Resource private RedisTemplate<String, Object> redisTemplate; @Test public void contextLoads() { Set<String> keySet = new HashSet<>(); for (int i = 0; i < 100000; i++) { String key = TYPE_NAME + ":" + i; keySet.add(key); } long time = System.currentTimeMillis(); multiGet(keySet); System.out.println("redisTemplate.opsForValue().multiGet \t 耗时:" + (System.currentTimeMillis() - time)); // 排除,太慢了 // time = System.currentTimeMillis(); // getData(keySet); // System.out.println("redisTemplate.opsForValue().get \t\t 耗时:" + (System.currentTimeMillis() - time)); // 推荐 time = System.currentTimeMillis(); getDataByPipelined(keySet); System.out.println("redisTemplate.executePipelined \t\t\t 耗时:" + (System.currentTimeMillis() - time)); } private void multiGet(Set<String> keySet) { redisTemplate.opsForValue().multiGet(keySet); } private void getData(Set<String> keySet) { for (String key : keySet) { redisTemplate.opsForValue().get(key); } } private void getDataByPipelined(Set<String> keySet) { redisTemplate.executePipelined((RedisCallback<Object>) redisConnection -> { for (String key : keySet) { redisConnection.get(key.getBytes(StandardCharsets.UTF_8)); } return null; }); } }
输出结果
redisTemplate.opsForValue().multiGet 耗时:422 redisTemplate.executePipelined 耗时:177
推荐方式
private void getDataByPipelined(Set<String> keySet) { redisTemplate.executePipelined((RedisCallback<Object>) redisConnection -> { for (String key : keySet) { redisConnection.get(key.getBytes(StandardCharsets.UTF_8)); } return null; }); }