springboot緩存的使用實踐
spring針對各種緩存實現(xiàn),抽象出了CacheManager接口,用戶使用該接口處理緩存,而無需關(guān)心底層實現(xiàn)。并且也可以方便的更改緩存的具體實現(xiàn),而不用修改業(yè)務(wù)代碼。下面對于在springboot中使用緩存做一簡單介紹:
1、添加依賴
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency>
2、在配置類里開啟緩存,如下圖所示:

3、在需要使用緩存的方法上加上注解,如下:
@Override
//@CachePut 該注解會將方法的返回值緩存起來,其中緩存名字是 people,數(shù)據(jù)的key是person的id
@CachePut(value = "people", key = "#person.id")
public Person save(Person person) {
Person p = personRepository.save(person);
System.out.println("為id、key為:"+p.getId()+"數(shù)據(jù)做了緩存");
return p;
}
@Override
//@CacheEvict 該注解會刪除people緩存中key為id 的數(shù)據(jù)
@CacheEvict(value = "people", key = "#id")
public void remove(Long id) {
System.out.println("刪除了id、key為"+id+"的數(shù)據(jù)緩存");
//這里不做實際刪除操作
}
@Override
//@Cacheable 該注解會在方法執(zhí)行時,判斷緩存people中key為#person.id
的緩存是否存在,如果存在,則直接返回緩存中的數(shù)據(jù)。如果不存在,則會查數(shù)據(jù)庫,然后將返回結(jié)果緩存起來。
@Cacheable(value = "people", key = "#person.id")
public Person findOne(Person person) {
Person p = personRepository.findOne(person.getId());
System.out.println("為id、key為:"+p.getId()+"數(shù)據(jù)做了緩存");
return p;
}
以上幾部就完成了緩存,但是現(xiàn)在的緩存是默認的基于內(nèi)存的,沒有實現(xiàn)持久化。下面以redis作為緩存的具體實現(xiàn),如下:
4、添加依賴
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-redis</artifactId> </dependency>
5、在配置文件里添加redis配置
redis.hostname=localhost redis.port=6379
6、在spring容器中配置redis
@Configuration
public class RedisConfig extends CachingConfigurerSupport{
private static final Logger logger = LoggerFactory.getLogger(RedisConfig.class);
@Autowired
private Environment env;
@Bean
public JedisConnectionFactory redisConnectionFactory() {
JedisConnectionFactory redisConnectionFactory = new JedisConnectionFactory();
redisConnectionFactory.setHostName(env.getProperty("redis.hostname"));
redisConnectionFactory.setPort(Integer.parseInt(env.getProperty("redis.port")));
return redisConnectionFactory;
}
@Bean
public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory cf) {
RedisTemplate<String, String> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(cf);
return redisTemplate;
}
@Bean
public CacheManager cacheManager(RedisTemplate<?, ?> redisTemplate) {
RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
cacheManager.setDefaultExpiration(600);
return cacheManager;
}
}
ok,完成了,其他什么都不用改,是不是很方便?
另外,要緩存的類必須序列化。
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
MyBatis的JdbcType與Oracle、MySql數(shù)據(jù)類型一覽表
這篇文章主要介紹了MyBatis的JdbcType與Oracle、MySql數(shù)據(jù)類型一覽表,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-01-01

