Spring Cache与Redis结合使用

本文介绍了如何将Spring Cache与Redis相结合,用于提高查询效率。通过创建Spring Boot项目并集成Redis,展示了如何配置CacheManager,使用@Cacheable和@CacheEvict注解进行缓存操作,并提供测试用例证明其效果。
摘要由CSDN通过智能技术生成

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,需要添加RedisCacheLombok库。

集成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<
  • 6
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值