关于测试从redis和本地数据库中拿数据的延时

因为主要测试从数据库中拿数据,所以在redis中,我只写了存取数据的方法,代码如下:

    public class TestRedisTime {
    
        private final JedisPool jedisPool;
    
        private final Logger logger = LoggerFactory.getLogger(this.getClass());
    
        private RuntimeSchema schema = RuntimeSchema.createFrom(Book.class);
    
        public TestRedisTime(String ip,int port){
            jedisPool = new JedisPool(ip,port);
        }
    //设置缓存
        public void setRedis(Book book){
            try {
                Jedis jedis = jedisPool.getResource();
                try {
                    String key = "Book:"+book.getBookId();
                    byte[] b = ProtostuffIOUtil.toByteArray(book,schema, LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE));
                    jedis.setex(key.getBytes(),3600,b);
                } finally {
                    jedis.close();
                }
    
            } catch (Exception e) {
                logger.error(e.getMessage(),e);
            }
        }
    //获取缓存
        public Book getRedis(int book_id){
            try {
                Jedis jedis = jedisPool.getResource();
                try {
                    String key = "book:"+book_id;
                    byte[] b = jedis.get(key.getBytes());
                    if (b != null){
                        Book book = schema.newMessage();
                        ProtostuffIOUtil.mergeFrom(b,book,schema);
                        return book;
                    }
                }finally {
                    jedis.close();
                }
            } catch (Exception e) {
                logger.error(e.getMessage(),e);
            }
            return null;
        }
    }

redis核心代码写好后,就是直接测试了,测试代码如下:

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration("classpath:spring/spring-dao.xml")
    public class BookDaoTest {
    
        @Autowired
        BookDao bookDao;
    
        @Autowired
        TestRedisTime redisTime;
    
        @Test
        public void selectBook() {
            Date date1 = new Date();
            Book book = bookDao.selectBook(1);
            Date date2 = new Date();
            System.out.println("before:"+(date2.getTime()-date1.getTime()));
            redisTime.setRedis(book);
            Date date3 = new Date();
            redisTime.getRedis(1);
            Date date4 = new Date();
            System.out.println("after:"+(date4.getTime()-date3.getTime()));
        }
    }

最后控制台输出的结果如下图所示:


image.png

简直快的一批,这还只是对比本地数据库和本地redis缓存之间的差异,要是算上网络时延,应该会更高些
可见缓存机制还是挺强大的。

你可能感兴趣的:(关于测试从redis和本地数据库中拿数据的延时)