This is for me to learn concepts like TCP, RESP and understand redis better. I used the blog Write your own miniature Redis with Python on charlesleifer.com
Uses RESP Protocol (Redis Serialization protocol)
| Data Type | Prefix | Structure | Example |
|---|---|---|---|
| Simple String | + |
+{string data}\r\n |
+this is a simple string\r\n |
| Error | - |
-{error message}\r\n |
-ERR unknown command "FLUHS"\r\n |
| Integer | : |
:{the number}\r\n |
:1337\r\n |
| Binary | $ |
${number of bytes}\r\n{data}\r\n |
$6\r\nfoobar\r\n |
| Array | * |
*{number of elements}\r\n{0 or more of above}\r\n |
*3\r\n+a simple string element\r\n:12345\r\n$7\r\ntesting\r\n |
| Dictionary | % |
%{number of keys}\r\n{0 or more of above}\r\n |
%3\r\n+key1\r\n+value1\r\n+key2\r\n*2\r\n+value2-0\r\n+value2-1\r\n:3\r\n$7\r\ntesting\r\n |
| NULL | $ |
$-1\r\n (string of length -1) |
$-1\r\n |
Client → SYN → Server ("I want to connect") - SYN = Synchronize Client ← SYN-ACK ← Server ("OK, I acknowledge") - SYN-ACK = SYN(its own sequence number), ACK (acknowledges client’s number) Client → ACK → Server ("Great, we're connected") - ACK confirming server’s sequence number
Normally each connection would need its own thread. Gevent uses green threads (lightweight coroutines) instead, so 64 clients can be handled concurrently without the overhead of 64 real OS threads.
A socket is basically just a door that lets two programs talk to each other over a network AF_INET just means "use the internet (IPv4)" SOCK_STREAM means "keep the line open continuously" (as opposed to sending one-off messages)
Without sockets, two programs have no way of talking to each other at all. It's the most fundamental building block of all network communication
-
terminal 1 python skeleton.py
-
terminal 2 python
from skeleton import Client
c = Client()
c.set('name', 'Alice') # returns 1
c.get('name') # returns 'Alice'
c.delete('name') # returns 1
c.get('name') # returns None
c.mset('a', '1', 'b', '2') # set multiple keys at once
c.mget('a', 'b') # returns ['1', '2']
c.flush() # clears all keys, returns count of deleted keys