Redis 安装与使用
❝Redis 是完全开源免费的,遵守BSD协议,是一个高性能的key-value数据库。
❞
Redis 与其他 key - value 缓存产品有以下三个特点:
- Redis支持数据的持久化,可以将内存中的数据保存在磁盘中,重启的时候可以再次加载进行使用。
- Redis不仅仅支持简单的key-value类型的数据,同时还提供list,set,zset,hash等数据结构的存储。
- Redis支持数据的备份,即master-slave模式的数据备份。
数据结构
Redis可以存储键与5种不同数据结构类型之间的映射,这5种数据结构类型分别为String(字符串)、List(列表)、Set(集合)、Hash(散列)和 Zset(有序集合)。
结构类型 | 结构存储的值 | 读写能力 |
---|---|---|
String | 可以是字符串、整数或者浮点数 | 对整个字符串或者字符串的其中一部分执行操作;对象和浮点数执行自增(increment)或者自减(decrement) |
List | 一个链表,链表上的每个节点都包含了一个字符串 | 从链表的两端推入或者弹出元素;根据偏移量对链表进行修剪(trim);读取单个或者多个元素;根据值来查找或者移除元素 |
Set | 包含字符串的无序收集器(unorderedcollection),并且被包含的每个字符串都是独一无二的、各不相同 | 添加、获取、移除单个元素;检查一个元素是否存在于某个集合中;计算交集、并集、差集;从集合里卖弄随机获取元素 |
Hash | 包含键值对的无序散列表 | 添加、获取、移除单个键值对;获取所有键值对 |
Zset | 字符串成员(member)与浮点数分值(score)之间的有序映射,元素的排列顺序由分值的大小决定 | 添加、获取、删除单个元素;根据分值范围(range)或者成员来获取元素 |
Window 下安装
下载
下载地址:https://github.com/tporadowski/redis/releases
Redis 支持 32 位和 64 位。这个需要根据你系统平台的实际情况选择,这里我们下载 Redis-x64-xxx.msi文件。
安装
直接双击Redis-x64-xxx.msi文件安装即可。
修改密码
打开安装目录下的redis.windows-service.conf
文件,在文档的 # requirepass foobared
后面增加一行requirepass 123456
,即可配置访问密码为:123456。
重启Redis服务
SpringBoot中使用Redis
添加依赖包
在项目的pom.xml
中添加如下:
org.springframework.bootspring-boot-starter-data-redis
配置Redis数据库连接
在application.yml
中配置Redis数据库连接信息(application.properties
的话自行修改),如下:
spring:
# Redis 配置
redis:
# Redis数据库索引(默认为0)
database: 1
# Redis服务器地址
host: 127.0.0.1
# Redis服务器连接端口
port: 6379
# Redis服务器连接密码(默认为空)
password: 123456
jedis:
pool:
# 连接池最大连接数(使用负值表示没有限制)
max-active: 50
# 连接池最大阻塞等待时间(使用负值表示没有限制)
max-wait: 3000
# 连接池中的最大空闲连接
max-idle: 100
# 连接池中的最小空闲连接
min-idle: 0
# 连接超时时间(毫秒)
timeout: 1200
Redis配置类
package com.example.demo.config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.time.Duration;
/**
* ---------------------------
* Redis配置类 (RedisConfig)
* ---------------------------
* @author:ylh
* ---------------------------
*/
@Configuration
@EnableCaching
@Slf4j
public class RedisConfig {
private Duration timeToLive = Duration.ofDays(1);
@Bean
public RedisCacheManager cacheManager(RedisConnectionFactory connectionFactory){
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(this.timeToLive)
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(keySerializer()))
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(valueSerializer()))
.disableCachingNullValues();
RedisCacheManager redisCacheManager = RedisCacheManager
.builder(connectionFactory)
.cacheDefaults(config)
.transactionAware()
.build();
log.debug("自定义RedisCacheManager加载完成");
return redisCacheManager;
}
@Bean(name = "redisTemplate")
public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory){
RedisTemplate redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory);
redisTemplate.setKeySerializer(keySerializer());
redisTemplate.setHashKeySerializer(keySerializer());
redisTemplate.setValueSerializer(valueSerializer());
redisTemplate.setHashValueSerializer(valueSerializer());
log.debug("自定义RedisTemplate加载完成");return redisTemplate;
}private RedisSerializer keySerializer() {return new StringRedisSerializer();
}private RedisSerializer valueSerializer() {return new GenericJackson2JsonRedisSerializer();
}
}
Redis工具类
将RedisTemplate实例包装成一个工具类,便于在代码中对Redis进行操作。
package com.example.demo.service;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
* ---------------------------
* 操作Redis的工具类 (RedisService)
* ---------------------------
* @author:ylh
* ---------------------------
*/
@Component
public class RedisService {
@Resource
private RedisTemplate redisTemplate;//--------------------对key的操作--------------------/**
* 给指定的key指定缓存失效时间
*
* @param key 键
* @param time 时间(秒)
*/public Boolean expireKey(String key, long time) {if (time > 0) {return redisTemplate.expire(key, time, TimeUnit.SECONDS);
}return false;
}/**
* 根据key 获取过期时间
*
* @param key 键 不能为null
* @return 时间(秒) 返回0代表为永久有效
*/public Long getExpireByKey(String key) {return redisTemplate.getExpire(key, TimeUnit.SECONDS);
}/**
* 判断key是否存在
*
* @param key 键
* @return true 存在 false不存在
*/public Boolean hasKey(String key) {return redisTemplate.hasKey(key);
}/**
* 删除缓存
*
* @param key 可以传一个值 或多个
*/public void delKeys(String... key) {if (key != null && key.length > 0) {if (key.length == 1) {
redisTemplate.delete(key[0]);
} else {
redisTemplate.delete(Arrays.asList(key));
}
}
}//--------------------对key的字符串操作--------------------/**
* 普通字符串获取
*
* @param key 键
* @return 值
*/public Object getValue(String key) {return key == null ? null : redisTemplate.opsForValue().get(key);
}/**
* 普通字符串放入
*
* @param key 键
* @param value 值
*/public void setValue(String key, Object value) {
redisTemplate.opsForValue().set(key, value);
}/**
* 普通字符串放入并设置时间
*
* @param key 键
* @param value 值
* @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期
*/public void setValue(String key, Object value, long time) {if (time > 0) {
redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
} else {
setValue(key, value);
}
}/**
* 普通字符串放入,值递增
*
* @param key 键
* @param delta 要增加几(大于0)
* @return 递增后的值
*/public Long incr(String key, long delta) {if (delta 0) {throw new RuntimeException("递增因子必须大于0");
}return redisTemplate.opsForValue().increment(key, delta);
}/**
* 普通字符串放入,值递减
*
* @param key 键
* @param delta 要减少几(小于0)
* @return 递减后的值
*/public Long decr(String key, long delta) {if (delta 0) {throw new RuntimeException("递减因子必须大于0");
}return redisTemplate.opsForValue().increment(key, -delta);
}//--------------------Map的操作--------------------/**
* 根据hashKey获得hash,再根据key获得hash里的值
*
* @param hashKey hask的键 不能为null
* @param key 键 不能为null
* @return 值
*/public Object getValueByHashKey(String hashKey, String key) {return redisTemplate.opsForHash().get(hashKey, key);
}/**
* 根据hashKey获得hash
*
* @param key 键
* @return 对应的多个键值
*/public Map getHashByHashKey(String key) {return redisTemplate.opsForHash().entries(key);
}/**
* 根据key,将map里的值都放在hash里
*
* @param key 键
* @param map 对应多个键值
*/public void setHashByHashKey(String key, Map map) {
redisTemplate.opsForHash().putAll(key, map);
}/**
* 根据key,将map里的值都放在hash里,并设置时间
*
* @param key 键
* @param map 对应多个键值
* @param time 时间(秒)
*/public void setHashByHashKey(String key, Map map, long time) {
redisTemplate.opsForHash().putAll(key, map);if (time > 0) {
expireKey(key, time);
}
}/**
* 向一张hash表中放入数据,如果不存在将创建
*
* @param hashKey hask的键
* @param key 键
* @param value 值
*/public void setValueByHashKey(String hashKey, String key, Object value) {
redisTemplate.opsForHash().put(hashKey, key, value);
}/**
* 向一张hash表中放入数据,如果不存在将创建,并设置时间
*
* @param hashKey hask的键
* @param key 键
* @param value 值
* @param time 时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间
*/public void setValueByHashKey(String hashKey, String key, Object value, long time) {
redisTemplate.opsForHash().put(hashKey, key, value);if (time > 0) {
expireKey(hashKey, time);
}
}/**
* 删除hash表中的值
*
* @param hashKey hask的键 不能为null
* @param key 键 可以使多个 不能为null
*/public Long delHashValue(String hashKey, Object... key) {return redisTemplate.opsForHash().delete(hashKey, key);
}/**
* 判断hash表中是否有该项的值
*
* @param hashKey hask的键 不能为null
* @param key 键 不能为null
* @return true 存在 false不存在
*/public Boolean hashHasKey(String hashKey, String key) {return redisTemplate.opsForHash().hasKey(hashKey, key);
}/**
* hash递增 如果不存在,就会创建一个 并把新增后的值返回
*
* @param hashKey hask的键
* @param key 键
* @param by 要增加几(大于0)
* @return 新增后的值
*/public Double hashValueIncr(String hashKey, String key, double by) {return redisTemplate.opsForHash().increment(hashKey, key, by);
}/**
* hash递减
*
* @param hashKey hask的键
* @param key 键
* @param by 要减少几(小于0)
* @return 递减后的值
*/public Double hashValueDecr(String hashKey, String key, double by) {return redisTemplate.opsForHash().increment(hashKey, key, -by);
}//--------------------对key的set(无序)的操作--------------------/**
* 根据key获取Set中的所有值
*
* @param key 键
* @return Set
*/public Set getSetByKey(String key) {return redisTemplate.opsForSet().members(key);
}/**
* 根据value从一个set中查询,是否存在
*
* @param key 键
* @param value 值
* @return true 存在 false不存在
*/public Boolean setHasKey(String key, Object value) {return redisTemplate.opsForSet().isMember(key, value);
}/**
* 将数据放入set缓存
*
* @param key set键
* @param values 值 可以是多个
* @return 成功个数
*/public Long setSetValue(String key, Object... values) {return redisTemplate.opsForSet().add(key, values);
}/**
* 将set数据放入缓存
*
* @param key set键
* @param time 时间(秒)
* @param values 值 可以是多个
* @return 成功个数
*/public Long setSetValue(String key, long time, Object... values) {
Long count = redisTemplate.opsForSet().add(key, values);if (time > 0) {
expireKey(key, time);
}return count;
}/**
* 根据set的key获取set缓存的长度
*
* @param key 键
* @return 长度
*/public Long getSetSizeByKey(String key) {return redisTemplate.opsForSet().size(key);
}/**
* 移除值为value的
*
* @param key 键
* @param values 值 可以是多个
* @return 移除的个数
*/public Long setValueRemoveByKey(String key, Object... values) {return redisTemplate.opsForSet().remove(key, values);
}//--------------------对key的zset(有序集合)操作--------------------/**
* 向zset插入数据的分值
*
* @param key 键
* @param value 值
* @param score 分值
*/public Boolean setZsetValueAndScore(String key, Object value, double score) {return redisTemplate.opsForZSet().add(key, value, score);
}/**
* 获取set缓存的长度
*
* @param key 键
* @return 长度
*/public Long getZsetSize(String key) {return redisTemplate.opsForZSet().size(key);
}/**
* 移除值为value的
*
* @param key 键
* @param values 值 可以是多个
* @return 移除的个数
*/public Long zSetRemoveByValue(String key, Object... values) {return redisTemplate.opsForZSet().remove(key, values);
}//--------------------list操作,均为rightPush--------------------/**
* 根据key获取list缓存的内容
*
* @param key 键
* @param start 开始 0 是第一个元素
* @param end 结束 -1代表所有值
* @return 取出来的元素 总数 end-start+1
*/public List getListByKey(String key, long start, long end) {return redisTemplate.opsForList().range(key, start, end);
}/**
* 获取list缓存的长度
*
* @param key 键
* @return 长度
*/public Long getListSize(String key) {return redisTemplate.opsForList().size(key);
}/**
* 通过索引 获取list中的值
*
* @param key 键
* @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推
* @return 值
*/public Object getListValueByIndex(String key, long index) {return redisTemplate.opsForList().index(key, index);
}/**
* 将list放入缓存
*
* @param key 键
* @param value 值
*/public Long setList(String key, Object value) {return redisTemplate.opsForList().rightPush(key, value);
}/**
* 将list放入缓存,并指定过期时间
*
* @param key 键
* @param value 值
* @param time 时间(秒)
*/public Long setList(String key, Object value, long time) {if (time > 0) {
expireKey(key, time);
}return redisTemplate.opsForList().rightPush(key, value);
}/**
* 将list放入缓存,追加
*
* @param key 键
* @param value 值
*/public Long setList(String key, List value) {return redisTemplate.opsForList().rightPushAll(key, value);
}/**
* 将list放入缓存,追加
*
* @param key 键
* @param value 值
* @param time 时间(秒)
*/public Long setList(String key, List value, long time) {if (time > 0) {
expireKey(key, time);
}return redisTemplate.opsForList().rightPushAll(key, value);
}/**
* 根据索引修改list中的某条数据
*
* @param key 键
* @param index 索引
* @param value 值
*/public void updateListByIndex(String key, long index, Object value) {
redisTemplate.opsForList().set(key, index, value);
}/**
* 移除等于value的N个值
*
* @param key 键
* @param count 移除多少个
* @param value 值
* @return 移除的个数
*/public Long removeListVale(String key, long count, Object value) {return redisTemplate.opsForList().remove(key, count, value);
}
}
测试
写一个测试用例类来完成对Redis的读写:
package com.example.demo.redis;
import com.example.demo.service.RedisService;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
/**
* ---------------------------
* Redis测试类 (RedisTest)
* ---------------------------
* @author ylh
* @date 2020-08-27 09:30:00
* ---------------------------
*/
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class RedisTest {
@Autowired
private RedisService redisService;
/**
* 初始化
*/
@Before
public void initialize() {
// 存数据
redisService.setValue("abc", "123456");
}
/**
* 读取缓存数据
*/
@Test
public void testGetValue() {
if (redisService.hasKey("abc")) {
String value = redisService.getValue("abc").toString();
System.out.println(value);
} else {
System.out.println("未读取到缓存");
}
}
}
运行之前,先指定配置文件,避免无法注入配置导致运行报错。
进入IDEA的Run/Debug 配置页,找到从左边的菜单列表中找到,Defaults --》Junit,然后在Configuration选项卡中的Environment variables中添加配置spring.profiles.active=local
。
运行test方法后,控制台输出如下:
123456
可视化工具
可视化工具推荐:「Redis Desktop Manager」。
下载
链接:https://pan.baidu.com/s/195xQlQGIUZjE_7G_DTg8iA
提取码:7gn6
安装
点击下一步即可(注意更改安装目录)。
连接Redis服务器
打开软件:
即可看到刚才测试类存入的值:
❝海底月是天上月,眼前人是心上人。
❞