- 本文介绍redis的使用
本文介绍redis的使用
redis启动步骤
windows下安装redis下载网址 https://github.com/MicrosoftArchive/redis
安装完成后,到安装目录下运行
redis-cli.exe
shutdown
exit
redis-server.exe redis.windows.conf
获取配置 CONFIG GET *
设置端口 redis-server --port 6380
开启redis-cli运行 redis-cli -h 127.0.0.1 -p 6380
关闭redis redis-cli shutdown
说明
redis键命名规则,尽量采取database:tablenaem这种风格
5种数据类型
string 不能超过512MB
hash
list
set
zset
本文并没有涉及到分布式的,主要是因为本人,暂未涉及分布式的邻域
本文同时列出了如何在spring-boot中使用redis,使用的是jedis的链接客户端
spring-boot-starter-data-redis内置的是lettuce链接客户端,用法比较高级哈,jedis对于我这种菜鸡够用了
redis自增自减相关操作
incr counter 等效于++counter
decr counter 等效于--counter
incrby counter 5 等效于counter+=5
decrby counter 6 等效于counter-=6
incrbyfloat counter 10.1 等效于counter+=10.1
redis string
set操作
set name "yejiawei"
set name yejiawei nx 键存在设置不成功
set name yejiawei xx 键必须存在设置才会成功
set name yejiawei ex 10 设置键10秒后过期
set name yejiawei px 5000 设置键5000毫秒后过期
setex name 10 yejiawei 设置键10秒后过期
setnx name yejiawei 键存在设置不成功
mset name yejiawei age 18 sex boy 批量设置值
getset name yejiawei 获取name的原值
setrange name 2 ja 在指定的位置设置值,从0开始
getrange name 2 3 获取第2和第3个索引位的字符
get操作
get name 取键
mget name age sex 批量获取值
其他操作
append name haha 追加值
strlen name 获取字符串长度
redis hash
set操作
hset obj:1 a 1 为obj:1添加一对{a: 1}
hmset user:1 a 1 b 2 c 3 批量设置
get操作
hget obj:1 a 获取obj:1中的 a
hmget user:1 a b c 批量获取
其他操作
hdel obj:1 a 删除obj:1中的键
hlen obj:1 获取obj:1中键的个数
hexists user:1 a 判断是否存在
hkeys user:1 获取所有的键
hvals user:1 获取所有的键值
hgetall user:1 获取所有的键值对
hincrby user:1 a 10 自增整数
hincrbyfloat user:1 a 1.1 自增小数
hstrlen user:1 a 计算长度
redis list
set操作
rpush arr 1 2 3 4 5 设置列表
lpush arr 0 左插元素
rpush arr 10 右插元素
linsert arr before 1 100 在1之前插入100
linsert arr after 1 100 在1之后插入100
lset arr 1 10000 将索引位为1的设置成10000
get操作
lrange arr 0 -1 从左到右列出元素
lindex arr -1 获取最后一个元素
其他操作
llen arr 获取元素个数
lpop arr 左删一个元素
rpop arr 右删一个元素
lrem arr 1 5 从左到右删除一个5
lrem arr -1 5 从右到左删除一个5
lrem arr 0 5 删除所有的5
ltrim arr 0 2 删除索引0和2之间的所有元素
redis set
set元素不能重复,不能使用下标访问
set集合的相关操作
sadd myset a b c 添加元素
srem myset a 删除元素
scard myset 计算元素个数
sismember myset a 判断元素是否在集合中
srandmember myset 2 随机返回2的元素
spop myset 随机弹出元素
smembers myset 查看集合中的元素
sinter myset myset1 取两集合交集
sunion myset myset1 取两集合并集
sdiff myset myset1 取两集合差集
sinterstore extramyset myset myset1 将两集合差集保存在extramyset中
redis 有序集合
不允许元素重复,允许设置分值排序
有序集合相关操作
zadd arr 100 name 添加成员
zadd arr 101 name1 102 name2 103 name3
zadd arr nx 104 name4 必须不存在
zadd arr xx 104 name4 必须存在
zadd arr ch 104 name4 返回受影响元素个数
zadd arr incr 104 name4 自增
zcard arr 返回成员个数
zscore arr name1 获取成员分数
zrank arr name1 获取成员排名,从低到高
zrevrank arr name1 获取成员排名,从高到低
zrem arr name 删除
zincrby arr 1 name1 增加成员分数
zrange arr 1 3 withscores 返回排名是1和3的成员,从低到高
zrevrange arr 1 3 withscores 返回排名是1和3的成员,从高到低
zrangebyscore arr 100 105 withscores 返回指定分数之间的成员
zrangebyscore arr (100 +inf withscores 返回100正无穷之间的成员
zcount arr 100 105 返回指定分数之间元素个数
zremrangebyrank arr 1 2 删除排名1和2之间的元素,升序
zremrangebyscore arr 105 106 删除分数105和106之间的元素
键过期
expire name 10 设置键10秒后自动删除
ttl name 查看键剩余存活时间,秒
pttl name 查看键剩余存活时间,豪秒
expireat hello 1469980800 秒级过期时间戳
pexpire key milliseconds 毫秒级过期时间戳
pexpireat key milliseconds-timestamp 毫秒级时间戳timestamp
persist name 删除键的过期设置,直接set键也会导致过期时间失效
迁移键
第一种:
move key db 将键迁移到其他数据库
第二种:
dump key 序列化键,源redis实例
例如序列化的结果 "\x00\byejiawei\a\x00\xe5\xaats\x9fI\xc2\x81"
restore key ttl value 复原键,目标redis实例,其中ttl为过期时间,设置为0表示没有过期时间
例如复原键,restore namer 0 "\x00\byejiawei\a\x00\xe5\xaats\x9fI\xc2\x81"
第三种:
migrate 127.0.0.1 6370 name 0 1000 将name迁移到6370端口的0号数据库超时时间为1000毫秒
migrate 127.0.0.1 6370 name 0 1000 replace 替换已经存在的值
migrate 127.0.0.1 6370 "" 0 5000 keys age arr sex 迁移多个键
其他键的操作
keys * 列出所有键
keys [e]* 列出e开头的键
scan 0 也是遍历键,只不过它一次遍历一点,根据上一次执行返回的cursor执行下一次遍历
hscan obj:1 0 遍历hash中的键
sscan myset 0 遍历set中的键
zscan arr 0 遍历有序set中的键
dbsize 获取键的总个数
exists name 检查是否存在某个键,返回1或0
type name 返回键数据类型
object encoding arr 查看list集合,内部数据结构实现类型
del name 删除键,支持同时删除多个,以空格隔开
rename key newkey 重命名
renamenx key newkey 重命名,新键名不存在
randomkey 随机取一个键
数据库管理
多数据库
redis默认16个数据库,通过索引来切换数据库
select 10 进入第11个数据库
建议不要使用多数据库,可以使用多个redis实例搞定
数据库清除
flushdb 清除当前数据库
flushall 清楚所有数据库
redis配置
慢查询记录
slowlog-log-slower-than 10000 执行时间超过10000毫秒的命令会记录到日志中
slowlog-max-len 128 慢查询日志列表最大记录条数
config set slowlog-log-slower-than 20000
config set slowlog-max-len 1000
config rewrite 将设置保存到配置文件中
slowlog get 展示日志列表
slowlog len 列表条数
slowlog reset 日志重置
redis其他相关操作
事务
终止事务
multi
set name yejiawei
discard
提交事务
multi
set name yejiawei
exec
发布和订阅
subscribe channel:sports 订阅频道
publish channel:sports "Tim won the championship" 发布消息
unsubscribe channel:sports 取消订阅
psubscribe it* 订阅以it为开头的频道
pubsub channels 查看活跃频道,也就是至少有一个人订阅的频道
pubsub channels channel:*r* 包含r的频道
pubsub numsub channel:sports 查看频道订阅数
pubsub numpat 查看通过psubscribe形式订阅的订阅数
主从
slaveof 127.0.0.1 6379
redis在spring-boot中的配置和基本使用
说明
本部分内容,本人根据最新版的spring-boot-starter-data-redis配置,网上很多都是老的,bug很多
项目目录
依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<exclusions>
<exclusion>
<groupId>io.lettuce</groupId>
<artifactId>lettuce-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>2.6.0</version>
</dependency>
properties配置
# ===============================
# DATABASE
# ===============================
spring.datasource.url=jdbc:mysql://localhost:3306/mydb?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&useSSL=false&allowPublicKeyRetrieval=true
spring.datasource.username=root
spring.datasource.password=123
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
server.tomcat.uri-encoding=UTF-8
server.port=9001
mybatis.mapper-locations=classpath:mapperxml/*.xml
# ===============================
# REDIS
# ===============================
spring.redis.host=localhost
spring.redis.port=6379
#spring.redis.password=root #根据需要
# 连接超时时间(毫秒)
spring.redis.timeout=10000
# Redis默认情况下有16个分片,这里配置具体使用的分片,默认是0
spring.redis.database=0
# 连接池最大连接数(使用负值表示没有限制) 默认 8
spring.redis.lettuce.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制) 默认 -1
spring.redis.lettuce.pool.max-wait=-1
# 连接池中的最大空闲连接 默认 8
spring.redis.lettuce.pool.max-idle=8
# 连接池中的最小空闲连接 默认 0
spring.redis.lettuce.pool.min-idle=0
RedisConfig
package com.springlearn.learn.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.GenericToStringSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@Configuration
public class RedisConfig {
@Bean
JedisConnectionFactory jedisConnectionFactory() {
return new JedisConnectionFactory();
}
@Bean
RedisTemplate< String, Object > redisTemplate() {
final RedisTemplate< String, Object > template = new RedisTemplate< String, Object >();
template.setConnectionFactory( jedisConnectionFactory() );
template.setKeySerializer( new StringRedisSerializer() );
template.setHashValueSerializer( new GenericToStringSerializer< Object >( Object.class ) );
// template.setValueSerializer( new GenericToStringSerializer< Object >( Object.class ) );
template.setValueSerializer( new GenericJackson2JsonRedisSerializer() ); // 序列化json,反序列化时直接强转就行了
return template;
}
}
TestController
package com.springlearn.learn.controller;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SessionCallback;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestController {
@Autowired
private RedisTemplate<String, Object> template;
@Autowired
private JdbcTemplate jdbcTemplate;
@ResponseBody
@RequestMapping(value = "/test1/{id}", method = RequestMethod.GET, produces = "application/json")
public List<Map<String, Object>> Test1(HttpServletRequest request, @PathVariable int id){
// 序列化
// 直接这样设置,会调用GenericJackson2JsonRedisSerializer序列化,对象
// String sql = "select * from test";
// List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
// template.opsForValue().set("obj", list);
// 第一种使用方式
// 直接访问template中的方法即可
// ListOperations<String, Object> listOps = template.opsForList();
// List<Object> list = listOps.range("arr", 0, -1);
// 第二种方式
// 调用Callback直接访问链接对象
// return template.execute(new RedisCallback<Object>() {
// public Object doInRedis(RedisConnection connection) throws DataAccessException {
// Long size = connection.dbSize();
// // Can cast to StringRedisConnection if using a StringRedisTemplate
// // 这里你可以访问和redis的api,方法基本同名
// // 如果你操作字符串比较多建议使用StringRedisTemplate
// connection.set("key".getBytes(), "value".getBytes());
// return connection.get("key".getBytes());
// }
// });
// 第三种方式
// 使用事务
List<Object> txResults = template.execute(new SessionCallback<List<Object>>() {
public List<Object> execute(RedisOperations operations) throws DataAccessException {
operations.multi();
template.opsForValue().get("obj");
return operations.exec();
}
});
return (List<Map<String, Object>>)txResults.get(0);
}
}
结尾
本篇文章花了本人较多的时间,搜索了N多国内外资料,最后整理出来的
如果有你想知道但是上面没有的,请提出来,我试着帮你们解决,更加完善本文