SpringBoot中RedisTemplate的GET性能测试

测试代码如下,为了更好体验测试结果每种模式分别执行了三遍

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;

@RunWith(SpringRunner.class)
@SpringBootTest
public class RedisTests {
    private static final String TYPE_NAME = RedisTests.class.getTypeName();

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Test
    public void contextLoads() {
        long time = System.currentTimeMillis();
        initData();
        initData();
        initData();
        System.out.println("redisTemplate.opsForValue().set 耗时:" + (System.currentTimeMillis() - time));

        time = System.currentTimeMillis();
        initDataByPipelined();
        initDataByPipelined();
        initDataByPipelined();
        System.out.println("redisTemplate.executePipelined 耗时:" + (System.currentTimeMillis() - time));
    }

    private void initData() {
        for (int i = 0; i < 10000; i++) {
            String key = TYPE_NAME + ":" + i;
            redisTemplate.opsForValue().set(key, key);
        }
    }

    private void initDataByPipelined() {
        for (int i = 0; i < 10000; i++) {
            String key = TYPE_NAME + ":" + i;
            redisTemplate.executePipelined((RedisCallback<Object>) redisConnection -> redisConnection.set(key.getBytes(StandardCharsets.UTF_8), key.getBytes(StandardCharsets.UTF_8)));
        }
    }

}

 

 

输出结果如下:

redisTemplate.opsForValue().set 耗时:125647
redisTemplate.executePipelined  耗时:137348

 

结果有点出乎意料,相同的网络环境,居然之家调用GET比使用pipeline性能略好

 

posted on 2021-12-15 10:59  小小程序员的梦想  阅读(736)  评论(1编辑  收藏  举报

导航