- 此工具类提供简单的key value存储和hash存储,使用的是StringRedisTemplate实现的
- 添加maven依赖:
<dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>3.3.0</version> </dependency> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-redis</artifactId> </dependency>
- 配置redis参数:
#redis spring.redis.timeout=5000 spring.redis.jedis.pool.max-active=200 spring.redis.jedis.pool.max-idle=10 spring.redis.jedis.pool.max-wait=10 spring.redis.jedis.pool.min-idle=5 spring.redis.jedis.pool.time-between-eviction-runs=50000 spring.redis.host=XXX spring.redis.password=XXX spring.redis.port=6379
- 具体代码:
import lombok.extern.slf4j.Slf4j; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Service; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.TimeUnit; @Slf4j @Service public class RedisService { private final StringRedisTemplate stringRedisTemplate; public RedisService(StringRedisTemplate stringRedisTemplate) { this.stringRedisTemplate = stringRedisTemplate; } //操作普通key,value public void set(String key, String value, long timeout, TimeUnit unit) { try { stringRedisTemplate.opsForValue().set(key, value, timeout, unit); } catch (Exception e) { log.error("set redis key: " + key + " error:", e); } } public Optional<String> get(String key) { try { return Optional.ofNullable(stringRedisTemplate.opsForValue().get(key)); } catch (Exception e) { log.error("get redis key: " + key + " error:", e); } return Optional.empty(); } public void del(String key) { try { stringRedisTemplate.delete(key); } catch (Exception e) { log.error("setWithExpireTime", e); } } //操作hash setName是hash表的名字 key是一个建 还可以存一个值 public void hSet(String setName,String key){ try { stringRedisTemplate.opsForHash().put(setName, key, "0"); }catch (Exception e){ log.error("hSet error",e); } } public void hIncrementBy(String setName,String key){ try { stringRedisTemplate.opsForHash().increment(setName,key,1); stringRedisTemplate.expire(setName,2,TimeUnit.DAYS); }catch (Exception e){ log.error("hincrby error",e); } } public Map<Object, Object> hGetAll(String setName){ try { return stringRedisTemplate.opsForHash().entries(setName); }catch (Exception e){ log.error("hgetall error",e); } return new HashMap<>(); } public Set<Object> hKeys(String setName){ try { return stringRedisTemplate.opsForHash().keys(setName); }catch (Exception e){ log.error("hkeys error",e); } return new HashSet<>(); } public Long hDel(String setName){ try { return stringRedisTemplate.opsForHash().delete(setName); }catch (Exception e){ log.error("hDel error",e); } return -1L; } }
- 注:打印日志使用了lombok插件