springboot集成redis, 簡單的key, value緩存操作.
1. application-local.properties
# redis on local
#spring.redis.port=6379
#spring.redis.host=localhost
#spring.redis.password=
#spring.redis.database=0
2. build.gradle
compile group: 'org.springframework.boot', name: 'spring-boot-starter-data-redis', version: '2.0.3.RELEASE'
3. StringRedisTemplate.java
@Slf4j
@Service
public class RedisStringServiceImpl implements RedisStringService {
@Resource
private StringRedisTemplate stringRedisTemplate;
private ValueOperations<String, String> valueOperations;
@PostConstruct
public void initOperations() {
valueOperations = stringRedisTemplate.opsForValue();
}
/**
* @param key String
* @param value String
* @param timeout seconds
*/
@Override
public void setWithExpire(String key, String value, long timeout) {
valueOperations.set(key, value, timeout, TimeUnit.SECONDS);
log.debug("Set to redis with expiration. key: {}, value: {}, timeout: {}.", key, value, timeout);
}
@Override
public String get(String key) {
return valueOperations.get(key);
}
}
4. Doc
link: https://docs.spring.io/spring-data/data-redis/docs/2.1.2.RELEASE/reference/html/#redis:template