Spring-Boot之Redis基础
准备
Redis下载地址:github.com/MSOpenTech/redis/releases
Redis数据库的默认端口号是 6379
开启Redis服务:cmd 命令窗口进入到redis目录下输入:
redis-server.exe redis.windows.conf
整合spring-boot 1.5.6
1.添加pom依赖
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-cache -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<!--
https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-redis
-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<version>1.4.3.RELEASE</version>
</dependency>
2.application.yml添加redis配置 注:redis配置在spring节点下
#redis配置
redis:
host: 127.0.0.1
port: 6379
pool:
max-idle: 20
min-idle: 1
max-active: 20
max-wait: 6000
database: 0
3.添加RedisConfiguration配置类
/**
* @ClassName RedisConfiguration
* @Description <redis缓存框架配置类>
* @Author zhaiyt
* @Date 2018/8/30 19:42
* @Version 1.0
*/
@Configuration
@EnableCaching
public class RedisConfiguration extends CachingConfigurerSupport {
private final Logger logger = LoggerFactory.getLogger(RedisConfiguration.class);
/**
* @return org.springframework.cache.CacheManager
* @Description <采用RedisCacheManager作为缓存管理器>
* @Author zhaiyt
* @Date 19:46 2018/8/30
* @Param [redisTemplate]
**/
@Bean
public CacheManager cacheManager(RedisTemplate redisTemplate) {
return new RedisCacheManager(redisTemplate);
}
/**
* @return org.springframework.cache.interceptor.KeyGenerator
* @Description <自定义生成key>
* @Author zhaiyt
* @Date 20:20 2018/8/30
* @Param []
**/
@Override
public KeyGenerator keyGenerator() {
return new KeyGenerator() {
@Override
public Object generate(Object o, Method method, Object... objects) {
StringBuilder sb = new StringBuilder();
sb.append(o.getClass().getSimpleName());
sb.append(method.getName());
for (Object arg : objects) {
sb.append(arg.toString());
}
logger.info("自定义Redis key :" + sb.toString());
return sb.toString();
}
};
}
}
4.添加必要注解
Service类上:@CacheConfig(cacheNames = "user")
方法上:@Cacheable
Test:
一定要将SQL打印到控制台,否则无法验证缓存是否生效
常用Redis客户端的简单命令:
Del key 删除指定key的值
Keys * 查看数据库所有key
Flushall 清空所有数据库
Quit 退出客户端连接