Spring Cache与Redis结合使用
前不久做了一个需要查询多,更新少的功能,老司机同事建议用Redis来做缓存,同时结合Spring Cache来做,特来总结下。
Redis
Redis 是一个高性能key-value数据库,个人感觉就像java中的Map,不过比它更加强大。
由于我用的是Mac,下面介绍如何安装Redis。
brew update
brew install redis
开启服务
brew services start redis
brew services list
下面是我本机的运行截图
创建Spring项目
我这边为了简单方便,直接使用了Spring Boot,直接用IntelJ Idea,需要添加Redis
、Cache
和Lombok
库。
集成Redis
集成Redis,直接在配置文件配置即可。
application.properties
#redis
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=
spring.redis.timeout=0
然后测试下Redis是否集成功。
@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringcacheApplicationTests {
@Autowired
StringRedisTemplate redisTemplate;
@Test
public void contextLoads() {
Assert.assertNotNull(redisTemplate);
redisTemplate.opsForValue().set("hello", "world");
String value = redisTemplate.opsForValue().get("hello");
log.info("value = " + value);
redisTemplate.delete("hello");
value = redisTemplate.opsForValue().get("hello");
log.info("value = " + value);
}
}
运行结果如下,如果没有出错,则表示集成功。
2017-11-19 14:56:10.075 INFO 73896 --- [ main] c.m.s.SpringcacheApplicationTests : value = world
2017-11-19 14:56:10.076 INFO 73896 --- [ main] c.m.s.SpringcacheApplicationTests : value = null<