springboot缓存的使用实践

  

弹簧针对各种缓存实现,抽象出了缓存管理器接口,用户使用该接口处理缓存,而无需关心底层实现,并且也可以方便的更改缓存的具体实现,而不用修改业务代码。下面对于在springboot中使用缓存做一简单介绍:

  

<强> 1,添加依赖

        & lt; dependency>   & lt; groupId> org.springframework.boot   & lt; artifactId> spring-boot-starter-cache   & lt;/dependency>   之前      

2,在配置类里开启缓存,如下图所示:

  

 springboot缓存的使用实践“> </p>
  <p> 3,在需要使用缓存的方法上加上注解,如下:</p>
  
  <pre类=   @Override//@CachePut该注解会将方法的返回值缓存起来,其中缓存名字是人,数据的关键是人的id   @CachePut(值=" https://www.yisu.com/zixun/people "键=" # person.id ")   公众人物保存(人){   人p=personRepository.save(人);   System.out.println(“为id,主要为:”+ p.getId() +“数据做了缓存”);   返回p;   }   之前            @Override//@CacheEvict该注解会删除人缓存中键为id的数据   @CacheEvict(值=" https://www.yisu.com/zixun/people "键=" # id”)   公共空间删除(id) {   System.out.println(“删除了id,关键为”+身份证+”的数据缓存”);//这里不做实际删除操作   }            @Override//@Cacheable该注解会在方法执行时,判断缓存人中主要为# person.id   的缓存是否存在,如果存在,则直接返回缓存中的数据。如果不存在,则会查数据库,然后将返回结果缓存起来。   @Cacheable(值=" https://www.yisu.com/zixun/people "键=" # person.id ")   公众人物findOne(人){   人p=personRepository.findOne (person.getId ());   System.out.println(“为id,主要为:”+ p.getId() +“数据做了缓存”);   返回p;   }      

以上几部就完成了缓存,但是现在的缓存是默认的基于内存的,没有实现持久化。下面以复述,作为缓存的具体实现,如下:

  

4,添加依赖

        & lt; dependency>   & lt; groupId> org.springframework.boot   & lt; artifactId> spring-boot-starter-redis   & lt;/dependency>   之前      

5,在配置文件里添加复述,配置

        redis.hostname=localhost   复述。端口=6379      

6,在春容器中配置复述,

        @ configuration   公开课RedisConfig延伸CachingConfigurerSupport {   私有静态最终日志记录器=LoggerFactory.getLogger (RedisConfig.class);      @ autowired   私人环境env;      @ bean   公共JedisConnectionFactory redisConnectionFactory () {   JedisConnectionFactory redisConnectionFactory=new JedisConnectionFactory ();   redisConnectionFactory.setHostName (env.getProperty (“redis.hostname”));   redisConnectionFactory.setPort (Integer.parseInt (env.getProperty (“redis.port”)));   返回redisConnectionFactory;   }      @ bean   公共RedisTemplate<字符串,String>redisTemplate (RedisConnectionFactory cf) {   String> RedisTemplate<字符串;,redisTemplate=new RedisTemplate<的在();   redisTemplate.setConnectionFactory (cf);   返回redisTemplate;   }      @ bean   公共缓存管理器缓存管理器(RedisTemplate<& # 63; & # 63;比;redisTemplate) {   RedisCacheManager cacheManager=new RedisCacheManager (redisTemplate);   cacheManager.setDefaultExpiration (600);   返回缓存管理器;   }      }   之前      

好的,完成了,其他什么都不用改,是不是很方便?

  

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

  

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

springboot缓存的使用实践