Redis is what is called a key-value store, often referred to as a NoSQL database. The essence of a key-value store is the ability to store some data, called a value, inside a key. This data can later be retrieved only if we know the exact key used to store it. We can use the command SET to store the value "fido" at key "server:name":
SET server:name "fido"
Redis will store our data permanently, so we can later ask "What is the value stored at key server:name?" and Redis will reply with "fido":
GET server:name => "fido"
Other common operations provided by key-value stores are DEL to delete a given key and associated value, SET-if-not-exists (called SETNX on Redis) that sets a key only if it does not already exist, and INCR to atomically increment a number stored at a given key:
SET connections 10
INCR connections => 11
INCR connections => 12
DEL connections
INCR connections => 1
There is something special about INCR. Why do we provide such an operation if we can do it ourself with a bit of code? After all it is as simple as:
x = GET count
x = x + 1
SET count x
The problem is that doing the increment in this way will only work as long as there is a single client using the key. See what happens if two clients are accessing this key at the same time:
- Client A reads count as 10.
- Client B reads count as 10.
- Client A increments 10 and sets count to 11.
- Client B increments 10 and sets count to 11.
We wanted the value to be 12, but instead it is 11! This is because incrementing the value in this way is not an atomic operation. Calling the INCR command in Redis will prevent this from happening, because it is an atomic operation. Redis provides many of these atomic operations on different types of data.
Redis can be told that a key should only exist for a certain length of time. This is accomplished with the EXPIRE and TTL commands.
SET resource:lock "Redis Demo"
EXPIRE resource:lock 120
This causes the key resource:lock to be deleted in 120 seconds. You can test how long a key will exist with the TTL command. It returns the number of seconds until it will be deleted.
TTL resource:lock => 113
// after 113s
TTL resource:lock => -2
The -2 for the TTL of the key means that the key does not exist (anymore). A -1 for the TTL of the key means that it will never expire. Note that if you SET a key, its TTL will be reset.
SET resource:lock "Redis Demo 1"
EXPIRE resource:lock 120
TTL resource:lock => 119
SET resource:lock "Redis Demo 2"
TTL resource:lock => -1
Redis also supports several more complex data structures. The first one we'll look at is a list. A list is a series of ordered values. Some of the important commands for interacting with lists are RPUSH, LPUSH, LLEN, LRANGE, LPOP, and RPOP. You can immediately begin working with a key as a list, as long as it doesn't already exist as a different type.
RPUSH puts the new value at the end of the list.
RPUSH friends "Alice"
RPUSH friends "Bob"
LPUSH puts the new value at the start of the list.
LPUSH friends "Sam"
LRANGE gives a subset of the list. It takes the index of the first element you want to retrieve as its first parameter and the index of the last element you want to retrieve as its second parameter. A value of -1 for the second parameter means to retrieve elements until the end of the list.
LRANGE friends 0 -1 => 1) "Sam", 2) "Alice", 3) "Bob"
LRANGE friends 0 1 => 1) "Sam", 2) "Alice"
LRANGE friends 1 2 => 1) "Alice", 2) "Bob"
LLEN returns the current length of the list.
LLEN friends => 3
LPOP removes the first element from the list and returns it.
LPOP friends => "Sam"
RPOP removes the last element from the list and returns it.
RPOP friends => "Bob"
Note that the list now only has one element:
LLEN friends => 1
LRANGE friends 0 -1 => 1) "Alice"
The next data structure that we'll look at is a set. A set is similar to a list, except it does not have a specific order and each element may only appear once. Some of the important commands in working with sets are SADD, SREM, SISMEMBER, SMEMBERS and SUNION.
SADD adds the given value to the set.
SADD superpowers "flight" SADD superpowers "x-ray vision" SADD superpowers "reflexes"
SREM removes the given value from the set.
SREM superpowers "reflexes"
SISMEMBER tests if the given value is in the set. It returns 1 if the value is there and 0 if it is not.
SISMEMBER superpowers "flight" => 1 SISMEMBER superpowers "reflexes" => 0
SMEMBERS returns a list of all the members of this set.
SMEMBERS superpowers => 1) "flight", 2) "x-ray vision"
SUNION combines two or more sets and returns the list of all elements.
SADD birdpowers "pecking" SADD birdpowers "flight" SUNION superpowers birdpowers => 1) "pecking", 2) "x-ray vision", 3) "flight"
Sets are a very handy data type, but as they are unsorted they don't work well for a number of problems. This is why Redis 1.2 introduced Sorted Sets.
A sorted set is similar to a regular set, but now each value has an associated score. This score is used to sort the elements in the set.
ZADD hackers 1940 "Alan Kay" ZADD hackers 1906 "Grace Hopper" ZADD hackers 1953 "Richard Stallman" ZADD hackers 1965 "Yukihiro Matsumoto" ZADD hackers 1916 "Claude Shannon" ZADD hackers 1969 "Linus Torvalds" ZADD hackers 1957 "Sophie Wilson" ZADD hackers 1912 "Alan Turing"
In these examples, the scores are years of birth and the values are the names of famous hackers.
ZRANGE hackers 2 4 => 1) "Claude Shannon", 2) "Alan Kay", 3) "Richard Stallman"
Simple strings, sets and sorted sets already get a lot done but there is one more data type Redis can handle: Hashes.
Hashes are maps between string fields and string values, so they are the perfect data type to represent objects (eg: A User with a number of fields like name, surname, age, and so forth):
HSET user:1000 name "John Smith" HSET user:1000 email "john.smith@example.com" HSET user:1000 password "s3cret"
To get back the saved data use HGETALL:
HGETALL user:1000
You can also set multiple fields at once:
HMSET user:1001 name "Mary Jones" password "hidden" email "mjones@example.com"
If you only need a single field value that is possible as well:
HGET user:1001 name => "Mary Jones"
Numerical values in hash fields are handled exactly the same as in simple strings and there are operations to increment this value in an atomic way.
HSET user:1000 visits 10
HINCRBY user:1000 visits 1 => 11
HINCRBY user:1000 visits 10 => 21
HDEL user:1000 visits
HINCRBY user:1000 visits 1 => 1
That wraps up the Try Redis tutorial. Please feel free to goof around with this console as much as you'd like.
Check out the following links to continue learning about Redis.
- Redis Documentation
- Command Reference
- Implement a Twitter Clone in Redis
- Introduction to Redis Data Types
相关推荐
这篇文章主要介绍了超强、超详细Redis入门教程,本文详细介绍了Redis数据库各个 方面的知识,需要的朋友可以参考下。
Redis是一个高性能的键值对存储数据库,它支持多种类型的数据结构,如字符串(strings)、列表(lists)、集合(sets)、有序集合(sorted sets)、哈希表(hash tables)等。这些数据结构都是基于内存的,因此Redis能够提供...
channels-redis有redis环境依赖,需要提前安装redis环境且版本>=5.0(可百度安装教程) python环境3.8、以及虚拟环境安装自行安装(建议安装虚拟环境) 有虚拟环境进入虚拟环境执行如下命令: pip install -r ...
根据提供的文档标题、描述、标签以及部分内容,我们可以深入探讨如何使用Redis实现一个简易的社交网站。下面将详细解析几个核心功能:关注用户、获取关注者列表、发布动态以及获取动态列表。 ### 一、使用Redis构建...
### Dubbo视频教程--高级篇--第24节--简易版支付系统介绍知识点 #### 1. Dubbo框架与分布式系统架构 Dubbo是一款高性能、轻量级的Java RPC框架,由阿里巴巴开源。它提供了高可用的服务治理能力,在分布式系统中尤为...
内容概要:本文提供了利用 Flask 框架与 Redis 数据库存储来实现的一个简单Web应用程序教程,该应用可以用于管理用户登录后的状态,存储用户的会话信息并在用户登出时删除相关数据。程序中涵盖了基本的功能如用户...
6. **缓存机制**:了解如何使用缓存提高系统性能,如使用Memcached或Redis。 7. **负载均衡**:如果项目规模扩大,可以学习如何配置负载均衡以应对高并发访问。 通过深入学习和实践StatusNet源代码,开发者不仅能...
功能包含:ip探活、port扫描、web指纹扫描、title扫描、压缩文件扫描、fofa获取、ms17010、mssql、mysql、postgres、redis、ssh、smb、rdp、telnet、tomcat等bp以及如netbios探测等功能。 2023年12月25日 v3.6 ...
更高级的实现可能使用负载均衡和分布式系统,例如使用Nginx分发请求,以及Redis等内存数据库存储用户会话。 3. **消息模型** 聊天室的消息模型通常是发布/订阅(Pub/Sub)模式。服务器作为中心节点,接收客户端的...
1、JavaQuarkBBS是一款使用Java编写的简易社区系统。 2、采用前后端分离的机制实现。前台项目通过http访问RESTFulAPI获取信息渲染页面。 3、项目技术分层明显,模块分离,采用springboot构建模块。 4、前台页面来自...
为了应对高并发访问,可以考虑使用缓存技术(如Memcached或Redis)存储部分数据,减少数据库压力。此外,投票系统可以进一步完善,例如添加用户登录、投票限制、IP跟踪等功能。 通过学习和实践这个简单的PHP投票...
MLlib,数据存储使用HDFS与Redis,可视化采用Flask、SocketIO、Echarts、Bootstrap 项目使用 简易使用说明 开箱即用,直接在v2目录中使用 python3 app.py # 开启后直接访问,即可使用该系统 http://127.0.0.1:5000...
在本套视频教程“27.第二十七套:Python分布式爬虫、信息检索、搜索引擎原理及应用”中,我们将深入探讨一系列与Web数据抓取、处理和搜索相关的高级技术。Python作为一门强大的编程语言,因其简洁易读的语法和丰富的...
它以其简易的结构和高效的性能,受到了许多开发者的欢迎。在本文中,我们将深入探讨douphp的核心特性、安装步骤、基本使用方法以及如何利用它来创建企业级网站。 一、douphp简介 douphp 是一款基于MVC(模型-视图-...
2. "简易java框架开源论坛系统" - 这个文件名可能代表项目的源代码或者项目说明。根据名字,我们可以推断这个BBS系统是基于一个简单的Java框架构建的,可能是Spring、Struts、Hibernate等。开源意味着代码可供公众...