1. install redis
unzip redis-4.0.9.tar.gz
go to redis folder, run:
make
make install
after make install, redis executable command are copied to /usr/local/bin
go to /usr/local/bin, run:
./redis-server
by default, redis-server is running on Terminal, we can change redis conf to make redis run a daemon thread.
```
daemonize yes
```
start redis by specifying conf file location
```
./redis-server /home/feiyy/redis-4.0.9/redis.conf
```
use redis-cli to connect redis server
```
./redis-cli
```
test redis:
```
127.0.0.1:6379> ping
```
to enable remote access:
```
./redis-cli -h 10.25.37.27 -p 6379 -a 123
```
modify config file
```
to comment the following line
#bind 127.0.0.1
change protected-mode from yes to no
protected-mode no
```
to add password
```
to uncomment requirepass
requirepass 123
```
2. Operates:
?設置一個 key 的過期時間(單位:秒)
expire name 10
?移除給定 key 的過期時間
persist name
?選擇數據庫
select
?將當前數據庫中的 key 轉移到其它數據庫中
move name 1
?返回值的類型
type name
?測試連接是否存活
ping
?返回當前數據庫中 key 的數目
dbsize
? 監視\--實時轉儲收到的請求
monitor
?刪除當前選擇數據庫中的所有 key
flushdb
?刪除所有數據庫中的所有 key
flashall
2.1 String
?set
–set name ljs
?Setnx:如果 key 已經存在,返回 0
–setnx name ljs
?Setex:指定此鍵值對應的有效期 ,時間單位為秒
setex user 100 ljs
?setrange :設置指定 key 的 value 值的子字符串 ,從指定的位置開始替換字符
setrange name 3 @gmail.com
?mset :一次設置多個 key 的值
mset key1 ljs key2 lkr
?getrange :獲取指定 key 的 value 值的子字符串
getrange name 0 6
mget :一次獲取多個 key 的值
mget key1 key2 key3
?incr:對 key 的值做加加操作
incr age
?incrby :同 incr 類似,加指定值
incrby age 5
?decr :對 key 的值做的是減減操作
decr age
?decrby :同 decr,減指定值
decrby age 5
?append :給指定 key 的字符串值追加 value,返回新字符串值的長度
append name @126.com
?strlen :取指定 key 的 value 值的長度
strlen name



2.2 hash
?hset :設置 hash field 為指定值
hset myhash name ljs
?hget :獲取指定的 hash field
hget myhash name
?Hmset:同時設置 hash 的多個 field
hmset myhash name ljs age 20
hmget :獲取全部指定的 hash filed
hmget myhash name age password
?hlen :返回指定 hash 的 field 數量
hlen myhash
?hdel
hdel myhash field1
?hkeys:返回 hash 的所有 field
hkeys myhash
?hvals :返回 hash 的所有 value
hvals myhash
hgetall :獲取某個 hash 中全部的 filed 及 value
hgetall myhash
2.3 list
2.4 set
1. unordered, no-repeated.
2. redis support to get union, intersect, diff of two sets
feiyy, friends: raven, steve,xx, yy, zz
niuniu, friends: raven, xx, tom, jack
because feiyy and niuniu have the same friends, so feiyy and niuniu could be friends.


2.5 zset
1. zset have value and weight, and redis can rank the order according to weight.
articles:
article1 380
article2 220
article3 500


3. Springboot connect to redis
3.1 simple operations for different data structure
pom.xml
```
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<version>2.1.3.RELEASE</version>
</dependency>
```
application.properties
```
spring.redis.database=0
spring.redis.host=10.25.37.27
spring.redis.port=6379
spring.redis.password=123
#spring.redis.jedis.pool.max-active=8
#spring.redis.jedis.pool.max-wait=-1
#spring.redis.jedis.pool.max-idle=8
#spring.redis.jedis.pool.min-idle=0
#spring.redis.timeout=100
```
controller
```
@Autowired
private RedisTemplate<String,String> redisTemplate;
@RequestMapping("/connect")
public String connectRedis()
{
//string
redisTemplate.opsForValue().set("spring", "test");
//hash
Map<String, String> m = new HashMap<>();
m.put("name", "feiyy");
m.put("password", "123");
redisTemplate.opsForHash().putAll("feiyy", m);
//list
redisTemplate.opsForList().leftPush("mylist", "item1");
redisTemplate.opsForList().leftPush("mylist", "item2");
//set
redisTemplate.opsForSet().add("myset", "set1");
redisTemplate.opsForSet().add("myset", "set2");
//zset
redisTemplate.opsForZSet().add("articles", "article001", 100);
redisTemplate.opsForZSet().add("articles", "article002", 200);
return "{\"result\":true}";
}
```
3.2 examples, get phone validation code, and check result
```
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.10/dist/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<div id="app">
<div>
<input type="text" placeholder="phone number" v-model="phonenumber">
<button type="button" @click="getcode">get code</button><span>{{returncode}}</span>
</div>
<div>
<input type="text" placeholder="code" v-model="code">
<button type="button" @click="login">login</button>
</div>
</div>
<script>
var vue = new Vue({
el:"#app",
data:{
phonenumber:"",
code:"",
returncode:""
},
methods:{
getcode:function()
{
axios.post('/redis/getcode',{
phonenumber:this.phonenumber
})
.then(response => {
console.log(response.data);
if(response.data.code)
{
this.returncode = response.data.code;
}
})
.catch(function (error) {
console.log(error);
});
},
login:function()
{
axios.post('/redis/checkcode',{
phonenumber:this.phonenumber,
code:this.code
})
.then(response => {
console.log(response.data);
//get the result, use router to go different pages
})
.catch(function (error) {
console.log(error);
});
}
}
})
</script>
</body>
</html>
```
```
@RequestMapping("/getcode")
public JSONObject getcode(@RequestBody JSONObject phonenumber)
{
String phone = phonenumber.getString("phonenumber");
JSONObject obj = new JSONObject();
if(redisTemplate.hasKey(phone+":count"))
{
//get key value
int count = Integer.parseInt(redisTemplate.opsForValue().get(phone+":count"));
if(count<100)
{
//2. found key, and less than 100 times
// incr 15940471397:count
redisTemplate.opsForValue().increment(phone+":count");
// generate 6 digits random number, set key in redis (15940471397:code,xxxxxx), expiretime 120 seconds
//generate 6 digits random number, set key in redis (15940471397:code,xxxxxx), expiretime 120 seconds
String code = "";
Random r = new Random();
for(int i=0; i<6;i++)
{
code = code + r.nextInt(10);
}
java.time.Duration d2 = java.time.Duration.ofSeconds(120);
redisTemplate.opsForValue().set(phone+":code", code,d2);
obj.put("code", code);
}
else
{
//3. found key, and >= 100 times
//return error message, exceed times
obj.put("error", "exceed 100 times");
}
}
else
{
//1. not found key,
//set key in redis (15940471397:count, 1), expiretime,
long now = System.currentTimeMillis() / 1000l;
long oneDaySeconds = 60 * 60 * 24;
long diff = oneDaySeconds - now % oneDaySeconds;
java.time.Duration d = java.time.Duration.ofSeconds(diff);
redisTemplate.opsForValue().set(phone+":count", "1", d);
//generate 6 digits random number, set key in redis (15940471397:code,xxxxxx), expiretime 120 seconds
String code = "";
Random r = new Random();
for(int i=0; i<6;i++)
{
code = code + r.nextInt(10);
}
//redisTemplate.opsForValue().set(phone+":code", code);
java.time.Duration d2 = java.time.Duration.ofSeconds(120);
redisTemplate.opsForValue().set(phone+":code", code,d2);
obj.put("code", code);
}
return obj;
}
```
```
@RequestMapping("/checkcode")
public JSONObject checkcode(@RequestBody JSONObject condition)
{
String phone = condition.getString("phonenumber");
String code = condition.getString("code");
JSONObject obj = new JSONObject();
if(redisTemplate.hasKey(phone+":code"))
{
//2. find code in redis, check if equal
String codeinredis = redisTemplate.opsForValue().get(phone+":code");
if(codeinredis.equals(code))
{
obj.put("result", "correct code");
}
else
{
obj.put("result", "wrong code");
}
}
else
{
//1. not find code in redis, assume the code expired
obj.put("result", "code expired");
}
return obj;
}
```
4. redis persistence
there are two ways of persistent:
snapshot(by default)
aop
?aof配置(in config file)
–appendonly yes
–appendfsync always
–appendfsync everysec
–appendfsync no
5. redis cluster

set up the environment
copy redis.conf, and create redis6380.conf, redis6381.conf, redis6382.conf
modify the following content
```
port 6380
pidfile /var/run/redis_6380.pid
dbfilename dump6380.rdb
appendfilename "appendonly6380.aof"
```

for slaves, in config file, add
```
slaveof localhost 6379
masterauth 123
```
start master and all slaves
./redis-server redis.conf
./redis-server redis6380.conf
./redis-server redis6381.conf
./redis-server redis6382.conf
use redis-cli to operate redis




now, when we set key-value in master, the data will be synchronized to all the slave.
- 第一章 Linux
- 1. Linux安裝和網絡配置
- 2. Linux基本命令
- 3. Xshell和winscp
- 4. VIM編輯器
- 5. 安裝軟件
- 5.1 安裝JDK
- 5.2 安裝TOMCAT
- 5.3 安裝MySql
- 5.4 安裝Nginx
- 5.5 部署工程
- 第二章 Nginx
- 1. 安裝Nginx
- 2. 配置Nginx
- 2.1 配置靜態服務器
- 2.2 配置反向代理
- 2.3 配置負載均衡
- 2.4 配置動靜分離
- 2.5 跨域訪問
- 第三章 Redis
- 1. 安裝Redis
- 2. JAVA操作Redis
- 3. Redis事務
- 4. Redis持久化
- 5. 主從復制和集群
- 6. Redis實現Session共享
- 第四章 MySQL主從復制
- 4.1 MyCat安裝
- 4.2 MySQL主從復制
- 4.3MySQL讀寫分離
- 第五章 ActiveMQ
- 5.1 Queue
- 5.2 Topic
- 第六章 FastDFS圖片服務器
- 第七章