使用springBoot添加redis缓存须要在POM文件里引入html
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-redis</artifactId> <version>1.4.3.RELEASE</version> </dependency>
咱们添加缓存的支持须要两个依赖,一个是SpringBoot内部的缓存配置、另外则是咱们的redis缓存。node
配置Redis数据库
依赖添加完成后,须要配置咱们本地的redis数据库链接到项目中,咱们打开application-local.properties配置文件添加以下图8所示的配置内容:redis
#redis spring.redis.cluster.nodes=172.0.0.1:6379 spring.redis.pool.max-active=20 spring.redis.pool.max-idle=10 spring.redis.pool.min-idle=5 spring.redis.pool.max-wait=10 spring.redis.timeout=5000
一、简易方式spring
@Configuration @EnableCaching public class RedisConfig extends CachingConfigurerSupport { //生成key @Override @Bean public KeyGenerator keyGenerator() { return new KeyGenerator() { @Override public Object generate(Object target, Method method, Object... objects) { return UserConstant.REDIS_KEY; //常量key } }; }
} 数据库
查看一下 Spring缓存注解@Cacheable、@CacheEvict、@CachePut使用参考
(http://www.javashuo.com/article/p-yfruwgfl-dm.html )
// serviceImpl 方法 @Cacheable("infos") 缓存
@Override @Cacheable("infos") public List<User> queryUser() { return this.UserMapper.queryUser(); }
如上只须要加上一个注解就能够 在调用查询的时候先去缓存里面找,没有就执行方法 而后再存到缓存里面app
在执行增、删、改的时候须要删除缓存以下:ide
@Override @CacheEvict("infos") public void editUserStatus(Map<String, Object> info) { UserMapper.editStatus(info); }
在对应的方法上加入注解 这样就会删除缓存spring-boot
最后去测试一下就能够。测试