首页 > 编程 > Java > 正文

springboot缓存的使用实践

2019-11-26 09:56:30
字体:
来源:转载
供稿:网友

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,完成了,其他什么都不用改,是不是很方便?

另外,要缓存的类必须序列化。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持武林网。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表