环境
操作系统:Windows 7 旗舰版
JDK:1.8.0_161
Eclipse:Mars.2 Release (4.5.2)
Spring Boot:1.5.17
步骤
1,引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
springboot1.4版本以前依赖为spring-boot-starter-redis,springboot1.4版本后依赖为spring-boot-starter-data-redis。
2,配置参数
我们利用spring-boot-autoconfiguration.jar包中已有的RedisAutoConfiguration.class类来获取RedisTemplate对象和StringRedisTemplate对象,这样我们只需要在application.properties中增加相应的参数就可以了。至于需要设置哪些参数,我们可以查看RedisProperties.class的源码(文件目录:spring-boot-autoconfigure-1.5.17.RELEASE.jar\org\springframework\boot\autoconfigure\data\redis),针对里面的配置项设置相应的值。示例如下:
# REDIS (RedisProperties)
# Redis数据库索引(默认为0)
spring.redis.database=0
# Redis服务器地址
spring.redis.host=172.16.0.104
# Redis服务器连接端口
spring.redis.port=6888
# Redis服务器连接密码(默认为空)
spring.redis.password=
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active=2000
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait=6000
# 连接池中的最大空闲连接
spring.redis.pool.max-idle=300
# 连接池中的最小空闲连接
spring.redis.pool.min-idle=100
# 连接超时时间(毫秒)
spring.redis.timeout=30000
3,增加Redis工具类,方便存取数据
@Component
public class RedisUtils {
@Autowired
StringRedisTemplate stringRedisTemplate;
public boolean set(String key, String value) {
try {
stringRedisTemplate.opsForValue().set(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public boolean set(String key, String value, long time, TimeUnit timeUnit){
try {
if(time>0){
stringRedisTemplate.opsForValue().set(key, value, time, timeUnit);
}else{
set(key, value);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public String get(String key){
return key==null?"":stringRedisTemplate.opsForValue().get(key);
}
}
工具类增加@Component是为了在使用的时候注入,里面的方法都不是静态的,因为StringRedisTemplate是动态注入的,写成静态方法会报错。
4,使用示例
下面是一个简单的使用示例
@RestController
public class LoginController {
@Autowired
RedisUtils redisUtils;
@RequestMapping("/login")
public String login() {
redisUtils.set("name", "shiyong");
return redisUtils.get("name");
}
}