【缓存】Redis入门

redis命令

命令行链接redis  redis-cli -h localhost -p 6478 -a password

keys * 可以查看系统中所有的key值,在开发环境非常有用的命令

select 0 可以用来切换数据库

 

redis官方介绍 https://redis.io/topics/data-types-intro

当我真正的接触到了Redis的时候,我被它的速度震惊了,因为它甚至比python内置的数据结构还要快。

 

在学习redis之前有几个问题可以先思考一下

1.系统的瓶颈出现在哪里?

IO读写,涉及到了磁盘操作,而这里速度是影响性能的主要因素

寄存器->内存->磁盘

依次是,存储量变大,但速度变慢。

2.NoSql是什么?

数据库有关系型数据库,结构化存储,支持SQL语句,这是我们所熟悉的,也是技术比较成熟的。

还有一种not only sql,例如redis通过key-value存储数据。

3.数据的持久化保存和速度之间的矛盾如何解决

要想持久化就不可避免的应用到磁盘,速度会下降,如何解决这两个矛盾呢?

 

Redis出现了,说起它的作者,你可能用过他写的另一个工具hping。

Redis有哪些特点?

1.数据可以存储到磁盘,提高可靠性

2.数据存放在内存中,可以定时保存到存储中。

3.多种数据结构的支持。

 

redis安装

在Mac上: brew install redis

在linux上通过源码编译安装。

redis本身没有提供windows版本,但微软公司维护了一份可在windows用的redis,但是网络好像不通。

从下面这个地址获取windos版本的编译好的二进制redis文件

https://github.com/dmajkic/redis/downloads

redis-server默认会占用系统的6379号端口。

redis有多种客户端,但其本质都是连接到server,然后执行命令。

 

redis的配置

redis.conf文件是配置文件。

 

redis的数据类型

字符串,列表,哈希,集合,有序集合

 

键与值在计算机术语中很常见了。

我通过python接口来学习了,初学者可以通过命令行进行学习

import redis

conn = redis.Redis()

 

1.字符串:

redis-cli中设置键和值 

set key value

获取键对应的值

get key

set 命令附带一些有用的选项,例如,当key存在的使用,我不想set成功,可以使用nx选项,也就是只有不存在时候才能设置成功

> set mykey newval nx

 

  • EX seconds -- Set the specified expire time, in seconds.
  • PX milliseconds -- Set the specified expire time, in milliseconds.
  • NX -- Only set the key if it does not already exist.
  • XX -- Only set the key if it already exist.

incr 命令

incr key 实现+1操作

incr 满足了原子性,也就是即使在并发情况下,incr也能准确计数

2.列表

Redis lists are implemented via Linked Lists. This means that even if you have millions of elements inside a list, the operation of adding a new element in the head or in the tail of the list is performed in constant time

> rpush mylist A
(integer) 1
> rpush mylist B
(integer) 2
> lpush mylist first
(integer) 3
> lrange mylist 0 -1
1) "first"
2) "A"
3) "B"

3.哈希表

 

4.集合

> sadd myset 1 2 3
(integer) 3
> smembers myset
1. 3
2. 1
3. 2

集合的并,交,差【就是数学中的并集,交集,差的概念】

key1 = {a,b,c,d}
key2 = {c}
key3 = {a,c,e}
key4 = {b}
SINTER key1 key2 key3 = {c}
SUNION key3 key4 = {a, b, c, e}
SDIFF key3 key = {a, e}

5.有序集合

 

6.位图

 

redis在项目工程的使用

无论在python项目还是java项目中,使用redis最好还是要通过连接池。并不是说直接使用不行,出于可控和性能的角度来讲要使用连接池

redis连接池java版

redis计数器

 

 

总结:对于我们不了解的技术总是心生畏惧,可但凡你投入几个小时学习一下,你就会发现一片崭新的天地。

posted @ 2022-03-06 10:39  叶常落  阅读(25)  评论(0编辑  收藏  举报