springboot集成redis
引入Maven依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
配置文件
#redis
spring.redis.database= 0
spring.redis.host= 127.0.0.1
spring.redis.port= 6379
spring.redis.password= 123456
spring.redis.jedis.pool.max-active= 8
spring.redis.jedis.pool.max-wait= -1
spring.redis.jedis.pool.max-idle= 8
spring.redis.jedis.pool.min-idle= 0
spring.redis.jedis.pool.timeout= 10000
代码整合Redis
RedisService
@Component
public class RedisService {
@Autowired
private StringRedisTemplate stringRedisTemplate;
public void set(String key, Object object, Long time) {
// 存放String 类型
if (object instanceof String) {
setString(key, object);
}
// 存放 set类型
if (object instanceof Set) {
setSet(key, object);
}
// 设置有效期 以秒为单位
stringRedisTemplate.expire(key, time, TimeUnit.SECONDS);
}
public void setString(String key, Object object) {
// 如果是String 类型
String value = (String) object;
stringRedisTemplate.opsForValue().set(key, value);
}
public void setSet(String key, Object object) {
Set<String> value = (Set<String>) object;
for (String oj : value) {
stringRedisTemplate.opsForSet().add(key, oj);
}
}
public String getString(String key) {
return stringRedisTemplate.opsForValue().get(key);
}
}
IndexController
@RestController
public class IndexControler {
@Autowired
private RedisService redisService;
@RequestMapping("/setString")
public String setString(String key, String value) {
redisService.set(key, value, 60l);
return "success";
}
@RequestMapping("/getString")
public String getString(String key) {
return redisService.getString(key);
}
@RequestMapping("/setSet")
public String setSet() {
Set<String> set = new HashSet<String>();
set.add("zhangsan");
set.add("lisi");
redisService.setSet("setTest", set);
return "success";
}
}