基本操作
General
# 返回给定模式的keys KEYS patter KEYS * # 返回全部 KEYS set* # 返回set开头的keys EXISTS key TYPE key DEL key
|
String
SET key value GET key # Set Extend Time SETEX key seconds value # Set When Key Not Exist SETNX key value
|
Hash
HSET key field value HGET key field HDEL key field # Get All Fields HKEYS key # Get All Values HVALS key
|
flowchart LR key[key] item[ field1: value1 field2: value2 ] key --> item
|
List
LPUSH key value1 value2 # Get Key From Start To Stop LRANGE key start stop # Right POP RPOP key # List Length LLEN key
|
Set
SADD key mem1 mem2 SMEMBERS key # Set Size SCARD key SINTER key1 key2 SUNION key1 key2 # Delete SREM key mem1 mem2
|
Sorted Set / ZSet
ZADD key score1 mem1 score2 mem2 # Show List ZRANGE key start stop (WITHSCORES) # Increse Member ZINCRBY key increment member ZREM key mem1 mem2
|
Redis for Java
- Jedis (Official Recommand)
- Lettuce
- Spring Data Redis
Redis Data Redis
pom.xml <dependency> <groupId>org.springframwork.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
|
application.ymlspring: redis: host: localhost port: 6379 password: yourPassword
|
@Configuration @Slf4j public class RedisConfiguration { @Bean public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) { log.info("开始创建Redis模板对象..."); RedisTemplate redisTemplate = new RedisTemplate(); redisTemplate.setConnectionFactory(redisConnectionFactory); redisTemplate.setKeySerializer(new StringRedisSerializer()); return redisTemplate; } }
|
持久化
RDB
# redis-cli save # 将会生成一个dump.rdb bgsave # 后台保存
|
AOF
保存执行的命令为日志。每次重启加载所有命令。
# redis.windows.conf appendonly yes appendsync always/everysec/no auto-aof-rewrite-percentage 100 auto-aof-rewrite-min-size 64mb
# redis-cli bgrewriteaof # 重新编排命令,让重启时执行更高效
|
事务
# 开始事务 multi
set key value # ... your command # 中途取消 discard
# 执行 exec
|
乐观锁
乐观锁:不认为别人会来抢占资源,所以会直接对数据进行操作,在操作时验证是否资源已被占用。
乐观锁会比较数据是否和原数据一致,一致,说明没有人抢占资源,可以修改。
watch key # 通过版本号,而不通过值来判断 unwatch key
|