Spring boot + redis 用RedisTemlate實現簡單的String key value 操作

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

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章