- 本文介紹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多國內外資料,最后整理出來的
如果有你想知道但是上面沒有的,請提出來,我試着幫你們解決,更加完善本文