Redis是一款开源的高级键值(key-value)缓存和内存存储系统,单线程运行,拥有较高的读写能力,可以用作网络化的内存缓存。
为了获取更高的IO性能,Redis在启动时会将所有的数据加载在内存中,而备份才会将数据持久化硬盘中。由此可见,Redis无法替代MySql或MongDB来作为数据库被使用,而适用于为高频读写的数据缓存提供服务。
在分布式环境下,为各个模块提供公共数据的共享服务,并且为单个服务提供缓存服务。
spring-boot-starter-data-redis封装了Jedis(Redis的java客户端)拥有丰富的Redis操作方式,并且针对热数据提供了缓存解决方案,只需简单的配置即可开箱使用。
1.2 Redis安装部署- Linux下安装
将下载好的安装包解压,使用Make命令编译Redis。
编译好后进入src目录,启动redis.sh。
- window下安装
下载zip安装包,解压后进入目录,双击redis.server.exe或使用cmd命令 redis-server.exe redis.window.conf 启动服务
1.3 Redis常用的方法@Autowired private StringRedisTemplate redisTemplate; private final String DEFAULT_KEY_PREFIX = ""; private final int EXPIRE_TIME = 1; private final TimeUnit EXPIRE_TIME_TYPE = TimeUnit.DAYS; publicvoid add(K key, V value) { try { if (value != null) { redisTemplate.opsForValue() .set(DEFAULT_KEY_PREFIX+key, JSON.toJSONString(value)); } } catch (Exception e) { log.error(e.getMessage(),e); throw new RuntimeException("数据缓存到redis失败"); } } public void add(K key, V value, long timeout, TimeUnit unit) { try { if (value != null) { redisTemplate.opsForValue() .set(DEFAULT_KEY_PREFIX+key, JSON.toJSONString(value), timeout, unit); } } catch (Exception e) { log.error(e.getMessage(),e); throw new RuntimeException("数据缓存到redis失败"); } } public void addHashCache(K key, SK SubKey, V value) { redisTemplate.opsForHash().put(DEFAULT_KEY_PREFIX+key, SubKey, value); } public void addHashCache(K key, SK SubKey, V value, long timeout, TimeUnit unit ) { redisTemplate.opsForHash().put(DEFAULT_KEY_PREFIX+key, SubKey, value); redisTemplate.expire(DEFAULT_KEY_PREFIX+key, timeout, unit); } public Object getHashCache(K key, SK SubKey ) { return redisTemplate.opsForHash().get(DEFAULT_KEY_PREFIX+key, SubKey); } public V getObject(K key, Class clazz ) { String value = this.get(key); V result = null; if (!StringUtils.isEmpty(value)){ result = JSONObject.parseObject(value,clazz); } return result; } public List getList(K key, Class clazz ) { String value = this.get(key); List result = Collections.emptyList(); if (!StringUtils.isEmpty(value)){ result = JSONObject.parseArray(value,clazz); } return result; } public String get(K key ) { String value; try { value = redisTemplate.opsForValue().get(DEFAULT_KEY_PREFIX+key); } catch (Exception e) { log.error(e.getMessage(), e); throw new RuntimeException("从redis缓存中获取缓存数据失败"); } return value; } public void delete(String key) { redisTemplate.delete(key); } public void delete(Collection keys) { redisTemplate.delete(keys); } public byte[] dump(String key) { return redisTemplate.dump(key); } public Boolean hashKey(String key) { return redisTemplate.hasKey(key); } public Boolean expire(String key, long timeout, TimeUnit unit ) { return redisTemplate.expire(key, timeout, unit ); } public Boolean expireAt(String key, Date date) { return redisTemplate.expireAt(key, date ); } public Boolean persist(String key, Date date) { return redisTemplate.persist(key); } public long getExpire(String key) { return redisTemplate.getExpire(key); }



