spring針對各種緩存實現,抽像出了CacheManager接口,用戶使用該接口處理緩存,而無需關心底層實現。並且也可以方便的更改緩存的具體實現,而不用修改業務代碼。下面對於在springboot中使用緩存做一簡單介紹:
1、添加依賴
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency>
2、在配置類裡開啟緩存,如下圖所示:
3、在需要使用緩存的方法上加上註解,如下:
@Override //@CachePut 該註解會將方法的返回值緩存起來,其中緩存名字是people,數據的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()+"數據做了緩存"); return p; } @Override //@CacheEvict 該註解會刪除people緩存中key為id 的數據@CacheEvict(value = "people", key = "#id") public void remove(Long id) { System.out.println("刪除了id、key為"+id+"的數據緩存"); //這裡不做實際刪除操作} @Override //@Cacheable 該註解會在方法執行時,判斷緩存people中key為#person.id 的緩存是否存在,如果存在,則直接返回緩存中的數據。如果不存在,則會查數據庫,然後將返回結果緩存起來。 @Cacheable(value = "people", key = "#person.id") public Person findOne(Person person) { Person p = personRepository.findOne(person.getId()); System.out.println("為id、key為:"+p.getId()+"數據做了緩存"); return p; }以上幾部就完成了緩存,但是現在的緩存是默認的基於內存的,沒有實現持久化。下面以redis作為緩存的具體實現,如下:
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,完成了,其他什麼都不用改,是不是很方便?
另外,要緩存的類必須序列化。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。