SpringBoot2.0.3 配置cache in Redis(超级简单)

使用SpringBoot2.0.3,真的很简单。分3步
1.导入starter-redis
2.在application.properties配置Redis
3.Application启动类配置
OK搞定

pom.xml导入spring-boot-starter-data-redis

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

指定Redis配置

修改application.properties文件

spring.redis.database=3
spring.redis.host=127.0.0.1
spring.redis.password=
spring.redis.jedis.pool.max-active=8
spring.redis.jedis.pool.max-idle=8
spring.redis.jedis.pool.max-wait=-1
spring.redis.jedis.pool.min-idle=2
spring.redis.port=6379

# config cache in redis
spring.cache.type=redis

Redis常用配置就不说了,说下spring.cache.type=redis,从官方文档中可以看出,主要是以下截图内容:
在这里插入图片描述
在缓存的提供者中,Redis的优先级比Simple(使用内存做缓存)高,即当导入starter-redis包,配置好Redis后,Redis默认就是存缓存的容器了,也即做到了cache in Redis。application.properties文件中的spring.cache.type=redis其实可以不用配置,但建议这样留着,一是为了让开发人员明白是redis做了缓存容器,同样也可以防止因为导入其他缓存容器包,会出现混淆的情况,毕竟Redis的优先级也不高

Application添加@EnableCaching

@SpringBootApplication
@EnableCaching
public class DemoCacheInRedisApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoCacheInRedisApplication.class, args);
    }

}

到这配置结束了,是不是超级简单

@Cacheable、@CachePut、@CacheEvict的简单介绍和使用

@Cacheable 优先从缓存中获取数据,如获取不到,再调用修饰的方法获取数据,然后缓存起来。比如下面的代码,先从Redis中获取数据,如果没有,再调用方法获取数据,并把数据缓存在Redis中

@Cacheable(value = "myCache", key = "1")
public List<String> cacheCacheable() {
	log.info("将数据存放在myCache缓存中");
	// 下面数据一般从数据库获取,这里只是演示说明,就不使用数据库了
	List<String> data = new ArrayList<>();
	data.add("hello");
	data.add("SpringBoot");
	return data;
}

上面@Cacheable(value = "myCache", key = "1")指定了缓存在Redis中的数据的key为myCache::1,如下
在这里插入图片描述

@CachePut 被@CachePut修改的方法每次都会执行,但在方法执行完后,会将返回结果存至缓存中。比如下面代码,方法执行后,将数据缓存到Redis中,其key为myCache::1

@CachePut(value = "myCache", key = "1")
public List<String> cacheCachePut(String newStr) {
	log.info("添加newStr至myCache中,并更新myCache缓存");
	// 如果使用数据库的话,更新数据时,需要同步更新数据库,这里只是演示说明,就不使用数据库了
	List<String> data = new ArrayList<>();
	data.add("hello");
	data.add("SpringBoot");
	data.add(newStr);
	return data;
}

@CacheEvict 从缓存中清除指定缓存。比如下面代码,方法被调用时,也清除了Redis中的key为myCache::1的缓存

@CacheEvict(value = "myCache", key = "1")
public String cacheCacheEvict() {
	log.info("清空myCache缓存");
	// 清空在Redis或内存中的缓存数据
	return "清空myCache缓存";
}

demo代码

Github

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值