| | |
| | | package cn.lili.cache.impl; |
| | | |
| | | import cn.lili.cache.Cache; |
| | | import lombok.RequiredArgsConstructor; |
| | | import lombok.extern.slf4j.Slf4j; |
| | | import org.springframework.beans.factory.annotation.Autowired; |
| | | import org.springframework.data.redis.connection.RedisConnection; |
| | | import org.springframework.data.redis.core.*; |
| | | import org.springframework.data.redis.support.atomic.RedisAtomicLong; |
| | |
| | | */ |
| | | @Slf4j |
| | | @Component |
| | | @RequiredArgsConstructor |
| | | public class RedisCache implements Cache { |
| | | |
| | | @Autowired |
| | | private RedisTemplate<Object, Object> redisTemplate; |
| | | |
| | | public RedisCache() { |
| | | |
| | | } |
| | | private final RedisTemplate<Object, Object> redisTemplate; |
| | | |
| | | @Override |
| | | public Object get(Object key) { |
| | |
| | | return entityIdCounter.getAndIncrement(); |
| | | } |
| | | |
| | | @Override |
| | | public Long decr(String key) { |
| | | RedisAtomicLong entityIdCounter = new RedisAtomicLong(key, redisTemplate.getConnectionFactory()); |
| | | return entityIdCounter.getAndDecrement(); |
| | | } |
| | | |
| | | |
| | | /** |
| | | * 使用Sorted Set记录keyword |
| | | * zincrby命令,对于一个Sorted Set,存在的就把分数加x(x可自行设定),不存在就创建一个分数为1的成员 |
| | |
| | | public Long zRemove(String key, String... value) { |
| | | return redisTemplate.opsForZSet().remove(key, value); |
| | | } |
| | | |
| | | /** |
| | | * 设置过期时间 |
| | | * |
| | | * @param key |
| | | * @param timeout 过期时长 |
| | | * @param timeUnit 时长单位 |
| | | */ |
| | | @Override |
| | | public void setExpire(String key, long timeout, TimeUnit timeUnit) { |
| | | redisTemplate.expire(key, timeout, timeUnit); |
| | | } |
| | | |
| | | /** |
| | | * 判断某个key是否存在 |
| | | * |
| | | * @param key |
| | | * @return |
| | | */ |
| | | @Override |
| | | public boolean exist(String key) { |
| | | return redisTemplate.hasKey(key); |
| | | } |
| | | } |