redis 详细讲解 & 入门教程

 ref: https://blog.csdn.net/liqingtx/article/details/60330555

1 什么是redis

Redis(Remote Dictionary Server),即远程字典服务(key - value 不就是一个字典么?),它是一个开源的、使用C语言编写的、支持网络交互的、可基于内存也可持久化的Key-Value数据库,通常被称为数据结构服务器,因为值(value)可以是字符串(String), 哈希(Map),列表(list),集合(sets)和有序集合(sorted sets)等类型。

2 redis有什么特点/ 优点?

1 异常快

每秒可执行大约110000次的设置(SET)操作,每秒大约可执行81000次的读取/获取(GET)操作

2 支持丰富的数据类型

Redis支持开发人员常用的大多数数据类型,例如列表,集合,排序集和散列等等。

这使得Redis很容易被用来解决各种问题,因为我们知道哪些问题可以更好使用地哪些数据类型来处理解决

3 操作具有原子性

所有Redis操作都是原子操作,这确保如果两个客户端并发访问,Redis服务器能接收更新的值

4 多实用工具/ 使用场景多

Redis是一个多实用工具,可用于多种用例,如:缓存,消息队列(Redis本地支持发布/订阅),应用程序中的任何短期数据,例如,web应用程序中的会话,网页命中计数等

 

Q: 为什么有以上这些优点?

1 内存数据库

Ref: https://blog.csdn.net/weixin_34032827/article/details/86032801

Ref: https://blog.csdn.net/xwx_100/article/details/82259787

 

名称

英文名称

数据存放位置

操作

速度

举例

内存数据库

MMDB:Main Memory

内存

操作内存

极快

redis

磁盘数据库

DRDB:Disk-Resident

磁盘

磁盘读写

一般

mysql

内存数据库(MMDB:Main Memory Database,也叫主存数据库)技术,从根本上抛弃了磁盘数据管理的许多传统方式,基于全部数据都在内存中管理进行了新的体系结构的设计(重新设计一种数据库管理系统),并且在数据缓存、快速算法、并行操作、数据恢复方面进行重新设计,以更有效地使用CPU周期和内存,这种技术近乎把整个数据库放进内存中,从而使数据处理速度比传统数据库快很多,一般都在10倍以上,理想情况甚至可以达到1000倍。

3 springBoot 如何集成redis?

Ref: https://blog.csdn.net/weixin_40623736/article/details/98097708

1 添加依赖

1 dependencies {
2     implementation 'org.springframework.boot:spring-boot-starter-web'
3     compile "org.springframework.boot:spring-boot-starter-data-redis"
4 }

2 application.yml文件配置 

1 spring:
2   redis:
3     host: localhost
4     port: 6379
5     password: xxx
6     timeout: 10000s
7     database: 07

 

4 redis基本使用

readis工具类

  1 package com.example.demo.cache;
  2 /*
  3  * THE MIT License
  4  */
  5 
  6 import org.springframework.beans.factory.annotation.Autowired;
  7 import org.springframework.data.redis.core.*;
  8 import org.springframework.data.redis.serializer.RedisSerializer;
  9 import org.springframework.data.redis.serializer.StringRedisSerializer;
 10 import org.springframework.stereotype.Component;
 11 
 12 import java.time.Duration;
 13 import java.util.*;
 14 import java.util.concurrent.TimeUnit;
 15 
 16 /**
 17  * @ClassName RedisUtils
 18  * @Description TODO
 19  * @Author Caesar
 20  * @Date2020/5/9 16:56
 21  * @Version V1.0
 22  **/
 23 @Component
 24 public class RedisUtils {
 25 
 26     public RedisTemplate redisTemplate;
 27 
 28     /**
 29      * 功能描述: 序列化key & value
 30      * @param redisTemplate
 31      * @Description TODO
 32      * @return void
 33      * @Author Caesar
 34      * @Date 22:08 2020/5/11
 35      **/
 36     @Autowired(required = false)
 37     public void setRedisTemplate(RedisTemplate redisTemplate) {
 38         RedisSerializer stringSerializer = new StringRedisSerializer();
 39         redisTemplate.setKeySerializer(stringSerializer);
 40         redisTemplate.setValueSerializer(stringSerializer);
 41         redisTemplate.setHashKeySerializer(stringSerializer);
 42         redisTemplate.setHashValueSerializer(stringSerializer);
 43         this.redisTemplate = redisTemplate;
 44     }
 45     //redis值(value)可以是字符串(String), 哈希(Map),列表(list),集合(sets)和有序集合(sorted sets)等类型
 46     /**
 47      * 功能描述: 查询
 48      * @param key key
 49      * @Description TODO
 50      * @return T
 51      * @Author Caesar
 52      * @Date 17:25 2020/5/9
 53      **/
 54 
 55     public <T>T getObject(String key){
 56         ValueOperations<String, T> operations = redisTemplate.opsForValue();
 57         return operations.get(key);
 58     }
 59     /**
 60      * 功能描述: 通过Key - value 存值
 61      * @param key
 62      * @param value
 63      * @Description TODO
 64      * @return org.springframework.data.redis.core.ValueOperations<java.lang.String,T>
 65      * @Author Caesar
 66      * @Date 17:48 2020/5/9
 67      **/
 68     public <T> ValueOperations<String, T> setObject(String key, T value){
 69         ValueOperations<String, T> operations = redisTemplate.opsForValue();
 70         operations.set(key, value);
 71         return operations;
 72     }
 73     /**
 74      * 功能描述:
 75      * @param key
 76      * @param value
 77      * @param timeout 过期时间
 78      * @param timeUnit 时间颗粒度
 79      * @Description TODO
 80      * @return org.springframework.data.redis.core.ValueOperations<java.lang.String,T>
 81      * @Author Caesar
 82      * @Date 18:15 2020/5/9
 83      **/
 84     public <T> ValueOperations<String, T> setExpirationObject(String key, T value, Integer timeout, TimeUnit timeUnit){
 85         ValueOperations<String, T> operations = redisTemplate.opsForValue();
 86         operations.set(key, value, timeout, timeUnit);
 87         return operations;
 88     }
 89 
 90     /**
 91      * 功能描述:
 92      * @param key
 93      * @Description TODO
 94      * @return java.util.List<T>
 95      * @Author Caesar
 96      * @Date 17:35 2020/5/9
 97      **/
 98     public <T> List<T> getList(String key){
 99         ListOperations<String, T> operations = redisTemplate.opsForList();
100         List<T> resultsList = new ArrayList<>();
101         Long size = operations.size(key);
102         for(int i = 0; i < size; i ++){
103             resultsList.add(operations.index(key, i));
104         }
105         return resultsList;
106     }
107     public <T> ListOperations<String, T> setList(String key, List<T> dataList){
108         ListOperations<String, T> operations = redisTemplate.opsForList();
109         if(dataList != null){
110             int size = dataList.size();
111             for(int i=0;i<size;i++){
112                 operations.leftPush(key, dataList.get(i));
113             }
114         }
115         return operations;
116     }
117 
118     /**
119      * 功能描述: 获取set类型的值
120      * @param key
121      * @Description TODO
122      * @return java.util.Set<T>
123      * @Author Caesar
124      * @Date 17:38 2020/5/9
125      **/
126     public <T> Set<T> getSet(String key){
127         Set<T> dataSet = new HashSet<T>();
128         BoundSetOperations<String, T> operations = redisTemplate.boundSetOps(key);
129         return operations.members();
130     }
131     public <T> BoundSetOperations<String, T> setSet(String key, Set<T> dataSet){
132         BoundSetOperations<String, T> operations = redisTemplate.boundSetOps(key);
133         Iterator<T> keySet = dataSet.iterator();
134         while(keySet.hasNext()){
135             operations.add(keySet.next());
136         }
137         return operations;
138     }
139     /**
140      * 功能描述: 获取map的值
141      * @param key
142      * @Description TODO
143      * @return java.util.Map<java.lang.String,T>
144      * @Author Caesar
145      * @Date 17:41 2020/5/9
146      **/
147     public <T> Map<String, T> getMap(String key){
148         Map<String, T> map = redisTemplate.opsForHash().entries(key);
149         return map;
150     }
151     public <T> HashOperations<String, String, T> setMap(String key, Map<String, T> map){
152         HashOperations hashOperations = redisTemplate.opsForHash();
153         if(map != null){
154             for(Map.Entry<String, T> entry : map.entrySet()){
155                 hashOperations.put(key, entry.getKey(), entry.getValue());
156             }
157         }
158         return hashOperations;
159     }
160     /**
161      * 功能描述: 存入有时效的单个值
162      * @param key
163      * @param value
164      * @param expire
165      * @Description TODO
166      * @return org.springframework.data.redis.core.ValueOperations<java.lang.String,T>
167      * @Author Caesar
168      * @Date 18:50 2020/5/9
169      **/
170     public <T> ValueOperations<String, T> setExpireKey(String key, T value, Duration expire){
171         ValueOperations valueOperations = redisTemplate.opsForValue();
172         valueOperations.set(key, value, expire);
173         return valueOperations;
174     }
175     /**
176      * 模糊匹配key
177      *
178      * @param pattern 字符串前缀
179      * @return 对象列表
180      */
181     public Collection<String> keys(String pattern) {
182         return redisTemplate.keys(pattern);
183     }
184 
185     public void deleteObject(String key){
186         redisTemplate.delete(key);
187     }
188     public void deleteCollection(String key){
189         redisTemplate.delete(key);
190     }
191 
192 }
View Code

 

测试类

 1 package com.example.demo.controller;
 2 /*
 3  * THE MIT License
 4  */
 5 
 6 import com.example.demo.cache.RedisCache;
 7 import com.example.demo.cache.RedisUtils;
 8 import org.springframework.beans.factory.annotation.Autowired;
 9 import org.springframework.web.bind.annotation.PathVariable;
10 import org.springframework.web.bind.annotation.PostMapping;
11 import org.springframework.web.bind.annotation.RequestMapping;
12 import org.springframework.web.bind.annotation.RestController;
13 
14 import java.time.Duration;
15 import java.util.*;
16 
17 /**
18  * @ClassName RedisTest
19  * @Description TODO
20  * @Author Caesar
21  * @Date2020/5/8 18:25
22  * @Version V1.0
23  **/
24 @RestController
25 public class RedisTest {
26 
27     @Autowired
28     private RedisCache redisCache;
29     @Autowired
30     private RedisUtils redisUtils;
31 
32     @RequestMapping("/redis/{key}/{value}")
33     public void login(@PathVariable String key, @PathVariable String value){
34         Map namesMap = new HashMap<String, Object>();
35         List<String> namesList = new ArrayList<String>();
36         Set<String> namesSet = new HashSet<>();
37         namesList.add("zhangsanfeng");
38         namesList.add("niubi");
39         namesList.add("cccckkkkk");
40         namesSet.add("zsf_set");
41         namesSet.add("dy_set");
42         namesSet.add("mark_set");
43         namesMap.put("map_key1", "map_value1");
44         namesMap.put("map_key2", "map_value2");
45         namesMap.put("map_key3", "map_value3");
46         Long expire = 30l;
47 
48         //redisUtils.setObject(key, value);
49         //redisUtils.setList(key, namesList);
50         //redisUtils.setSet(key, namesSet);
51         //redisUtils.setMap(key, namesMap);
52         //redisUtils.setExpireKey(key, value, Duration.ofSeconds(expire));
53         //redisUtils.deleteObject(key);
54 //        Map<String, Object> resultMap = redisUtils.getMap("nameMap");
55 //        for(Map.Entry<String, Object> entry : resultMap.entrySet()){
56 //            String keys = entry.getKey();
57 //            String values = entry.getValue().toString();
58 //            System.out.println("key is: "+keys+",value is: "+values);
59 //        }
60 //        List<String> list = redisUtils.getList("nameList");
61 //        for(String str: list){
62 //            System.out.println("the value of list is: "+ str);
63 //        }
64         Collection<String> li = redisUtils.keys("*name");
65         // 获取redis中所有的key
66         Collection<String> liss = redisUtils.keys("*");
67         Collection<String> lis = redisUtils.keys("name????");
68         for(String str : lis){
69             System.out.println("the keys return result is: "+ str);
70         }
71 
72     }
73 
74 }
View Code

5 什么场景下使用redis?

https://www.php.cn/redis/422103.html

https://blog.csdn.net/Bobdragery/article/details/99711762

6 -- redis持久化

如果设置了redis的持久化,那么redis会定时以追加(AOF)或者快照(RDB)的方式把数据持久化到硬盘中。

7 -- redis相关配置

8 -- redis高级

redis集群 / redis相关LIB库 / 缓存穿透 / 雪崩 / redis工作原理(键过期, 键淘汰策略) / redis源码/ redis存储原理

 

posted @ 2020-05-11 22:10  Caesar_the_great  阅读(473)  评论(0编辑  收藏  举报