ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
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 ![](https://box.kancloud.cn/5e6c8c02e0f2df0722f78f4b951591ad_298x630.png) ![](https://box.kancloud.cn/ecf574521fc34e8bae81b050038d0a07_324x624.png) ![](https://box.kancloud.cn/6d106185bd1fadadb8ddeeeaee2ad5f2_231x203.png) 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. ![](https://box.kancloud.cn/9c6bcdd10eb9be275faa92fb5d12d121_287x621.png) ![](https://box.kancloud.cn/a9fcf6d72a73773dc7a6fb54b52a6ba4_311x557.png) 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 ![](https://box.kancloud.cn/7804a4ab10952884266e7ec000860035_411x603.png) ![](https://box.kancloud.cn/c98d4c41928b95dea0362970ffd3da21_364x303.png) 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 ![](https://box.kancloud.cn/2f9a3b623e1e24344e7a1db351076c3e_614x408.png) 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" ``` ![](https://box.kancloud.cn/5877e76edb66b86efee31336ffe7d096_1135x44.png) 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 ![](https://box.kancloud.cn/6aec1ff7bcdb3efc93720f25ea4ba04f_394x270.png) ![](https://box.kancloud.cn/5545089d0cfd76d90c99165e42139994_398x301.png) ![](https://box.kancloud.cn/b8fd45412a1dc7b3fefd24847ebd6daf_396x304.png) ![](https://box.kancloud.cn/26643cd227993bee926f93900da736cc_393x302.png) now, when we set key-value in master, the data will be synchronized to all the slave.