springboot整合redis缓存

使用springBoot添加redis缓存需要在POM文件里引入

<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缓存。

配置Redis数据库
依赖添加完成后,需要配置我们本地的redis数据库连接到项目中,我们打开application-local.properties配置文件添加如下图8所示的配置内容:

#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

1、简易方式br/>@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {

//生成key br/>@Override
@Bean
public KeyGenerator keyGenerator() {
return new KeyGenerator() {
br/>@Override
public Object generate(Object target, Method method, Object... objects) {
return MumsInfoConstant.REDIS_KEY;
}
};
}
}

查看一下 Spring缓存注解@Cacheable、@CacheEvict、@CachePut使用参考
https://www.cnblogs.com/fashflying/p/6908028.html
// serviceImpl 方法 @Cacheable("infos") br/>@Override
@Cacheable("infos")
public List<User> queryUser() {
return this.UserMapper.queryUser();
}

如上只需要加上一个注解就可以 在调用查询的时候先去缓存里面找,没有就执行方法 然后再存到缓存里面

在执行增、删、改的时候需要删除缓存如下:br/>@Override
@CacheEvict("infos")
public void editUserStatus(Map<String, Object> info) {
UserMapper.editStatus(info);
}
在对应的方法上加入注解 这样就会删除缓存

最后去测试一下就可以。

猜你喜欢

转载自blog.51cto.com/11864647/2106688