缓存的使用

1. 引入依赖
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>
2. 在程序入口添加 @EnableCaching 注解
@Log4j2
@EnableCaching
@SpringBootApplication
@MapperScan(value = "com.liuzhihang.springboot.dao")
public class MySpringbootApplication {
    private static Logger logger = LogManager.getLogger(MySpringbootApplication.class);

    public static void main(String[] args) {
        SpringApplication.run(MySpringbootApplication.class, args);
        log.info("服务启动完成...!");
    }
}
3. 在要缓存的内容上添加 @Cacheable 注解
@Override
@Cacheable(value = "bonusInfo", key = "#transId")
public GoBonusInfo getBonusInfoByTransIdUseCache(String transId) {

    GoBonusInfoExample example = new GoBonusInfoExample();
    example.createCriteria().andTransIdEqualTo(transId);
    List<GoBonusInfo> bonusInfoList = bonusInfoMapper.selectByExample(example);
    return bonusInfoList.get(0);
}
4. 测试代码及结果
@RequestMapping("/cacheTest")
public String cacheTest(String transId, Integer flag) {
    GoBonusInfo bonusInfo = null;
    for (int i = 1; i <= 5; i++) {
        long startTime = System.currentTimeMillis();
        switch (flag) {
            case 0:
                bonusInfo = bonusInfoService.getBonusInfoByTransId(transId);
                break;
            case 1:
                bonusInfo = bonusInfoService.getBonusInfoByTransIdUseCache(transId);
                break;
            default:
        }
        log.info("第:{}次查询, 耗时:{} ", i, System.currentTimeMillis() - startTime);
    }

    return "OK";
}

// 结果如下:
flag = 0:
[2017-12-03 17:33:21:954]-[com ... -4] -[INFO ] - [:1次查询, 耗时:61 ]
[2017-12-03 17:33:22:035]-[com ... -4] -[INFO ] - [:2次查询, 耗时:81 ]
[2017-12-03 17:33:22:137]-[com ... -4] -[INFO ] - [:3次查询, 耗时:102 ]
[2017-12-03 17:33:22:230]-[com ... -4] -[INFO ] - [:4次查询, 耗时:93 ]
[2017-12-03 17:33:22:287]-[com ... -4] -[INFO ] - [:5次查询, 耗时:56 ]
flag = 1:
[2017-12-03 17:39:33:281]-[com ... -2] -[INFO ] - [:1次查询, 耗时:68 ]
[2017-12-03 17:39:33:282]-[com ... -2] -[INFO ] - [:2次查询, 耗时:0 ]
[2017-12-03 17:39:33:283]-[com ... -2] -[INFO ] - [:3次查询, 耗时:1 ]
[2017-12-03 17:39:33:284]-[com ... -2] -[INFO ] - [:4次查询, 耗时:1 ]
[2017-12-03 17:39:33:285]-[com ... -2] -[INFO ] - [:5次查询, 耗时:1 ]

   版权声明

文章作者: liuzhihang
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源!

评论
  目录