Redis installation
1, download, decompress, install
[root@incisor ~]# yum install -y gcc gcc-c++ make cmake
[root@incisor ~]Wget # http://download.redis.io/releases/redis-5.0.3.tar.gz
[root@incisor ~]# tar - ZXVF redis - 5.0.3. Tar. Gz
[root@incisor ~]# CD redis - 5.0.3[root @ incisor redis - 5.0.3]# make PREFIX=/usr/local/redis install
Copy the code
1) Copy the utils/redis_init_script file to /etc/init.d/ and rename it Redis
[root @ incisor redis - 5.0.3]# cp -p utils/redis_init_script /etc/init.d/redis[root @ incisor redis - 5.0.3]# vi /etc/init.d/redis
Copy the code
Modified contents:
REDISPORT=6379 Redis listener port is defined
EXEC=/usr/local/redis/bin/redis-server # redis The default server execution path
CLIEXEC=/usr/local/redis/bin/redis-cli # redis-cli startup path
PIDFILE=/var/run/redis_${REDISPORT}.pid
#redis configuration file, so we need to create a directory in /etc to save the redis configuration file, and copy the configuration file to this directory
CONF="/etc/redis/redis.conf" # redis configuration file
Copy the code
2) Copy the redis.conf file to /etc/redis/
[root @ incisor redis - 5.0.3]# mkdir /etc/redis[root @ incisor redis - 5.0.3]# cp -p redis.conf /etc/redis/[root @ incisor redis - 5.0.3]# vi /etc/redis/redis.conf
Copy the code
Modified contents:
bind 127.0.0.1 For remote access, change the IP address to a public IP address
daemonize yes # change to yes to run as a daemon
Copy the code
There are only two basic Settings, but I only want to use Redis as a cache, so I don’t need persistence, so I have to change some other Settings, the following Settings are as needed:
loglevel notice # log level
logfile "/usr/local/redis/log/redis.log" # Log save path
maxmemory 67108864 Set the maximum memory usage to 64M, as required
databases 1 # set the maximum number of databases
requirepass 12345678 # set password
#save 900 1
#save 300 10
#save 60 10000
save "" # turn off RDB persistence
appendonly no # Turn off AOF persistence
Copy the code
Create log directory /usr/local/redis/log.
3. Add system services
[root@incisor redis]# cd /etc/init.d/
[root@incisor init.d]# chkconfig --add redis
[root@incisor init.d]# chkconfig --level 235 redis on
[root@incisor init.d]# chkconfig --list redis #Redis 0: disabled 1: disabled 2: enabled 3: enabled 4: disabled 5: enabled 6: disabledCopy the code
The chkconfig deletion service is: chkconfig –del [name], for example, chkconfig –del redis.
4. Start and stop Redis
[root@incisor init.d]# service redis start
[root@incisor init.d]# service redis stop
Copy the code
If bind is set to a public IP address in /etc/redis/redis.conf, run the service redis stop command to stop the process.
The stop command executes the stop function in /etc/init.d/redis.
Among them
$CLIEXEC -p $REDISPORT shutdown
Copy the code
Is stop Redis task, and $CLIEXEC Redis – namely the cli command, ignore -h parameter, the default is to connect 127.0.0.1, so if the/etc/Redis/Redis in conf bind not 127.0.0.1, Then you need to modify the /etc/init.d/redis file. Modified as follows:
IP = 127.0.0.1/etc/redis/redis
REDISPORT=6379
EXEC=/usr/local/redis/bin/redis-server
CLIEXEC=/usr/local/redis/bin/redis-cli ...... omit$CLIEXEC -h $IP -p $REDISPORT shutdown -h $IP
Copy the code
But I generally use their own test, are too lazy to change, directly kill.
5. Access the cli client
[root@incisor ~]# /usr/local/redis/bin/redis-cli -h host -p port -a password
Copy the code
Python connection Redis
Pip3 install redis
Redis provides two classes redis and StrictRedis for implementing redis server commands. Redis is a subclass of StrictRedis for backward compatibility with older versions of Redis-py. So the Redis class is often used.
Redis connection instances are thread-safe and can be set as a global variable directly.
2. Connect to Redis server
import redis
r = redis.Redis(host='127.0.0.1', port=6379, decode_responses=True)
r.set('skey'.'svalue')
print(r['skey'])
print(r.get('skey'))
print(type(r.get('skey')))
Copy the code
Decode_responses =True is required so that value is STR or False is byte.
3. Connection pool
import redis
pool = redis.ConnectionPool(max_connections=10, host='127.0.0.1', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)
r.set('skey'.'svalue')
print(r['skey'])
print(id(r))
Copy the code
Max_connections: set the maximum number of connections. Here is a document that analyzes the source code of the redis.connectionpool () ConnectionPool, if you are interested: www.u3v3.com/ar/1346.
4. Set the connection pool to the singleton pool.py file
import redis
pool = redis.ConnectionPool(max_connections=10, host='127.0.0.1', port=6379, decode_responses=True)
Copy the code
Then, the other files import the pool variable so that you can implement a singleton connection pool. Test. Py files
import redis
from pool import pool
r = redis.Redis(connection_pool=pool)
r.set('skey'.'svalue')
print(r['skey'])
Copy the code
Specific Redis data type, as well as the corresponding method, to view.
Django uses Redis as a cache for relational databases
Pip3 install django-redis
2, set settings.py file to add
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache"."LOCATION": "Redis: / / 127.0.0.1:6379/0"."OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient"."CONNECTION_POOL_KWARGS": {"max_connections": 10, "decode_responses": True},
# "PASSWORD": ""}}}Copy the code
Where “LOCATION” represents the connection string and can be set in three ways: redis://[:password]@localhost:6379/0 rediss://[:password]@localhost:6379/0 unix://[:password]@/path/to/spcket.sock? Db =0 db=0 db=0 db=0 db=0 db=0 db=0 db=0 db=0 db=0
“CONNECTION_POOL_KWARGS”: connection pool Settings “max_connections”: maximum number of connections” decode_responses”: write Redis as a string or a byte type if False.
Django-redis uses the connection pool interface of Redis-py. By default, redis-py does not close connections and reuses connections whenever possible. Redis-py is the connection pool of the Redis library.
3. Redis can be accessed in two ways:
1) Use the django.core.cache.cache class, which has huge pits!
from django.core.cache import cache
from django.http import HttpResponse
def hello(request):
key = 'skey'
value = 'svalue'
cache.set(key, value)
if key in cache:
return HttpResponse('<h1>{0}: {1}</h1>'.format(key, cache.get(key)))
else:
return HttpResponse(' Not found
')
Copy the code
Before this code runs, the decode_responses parameter in CACHES in settings.py needs to be set to False for reasons I don’t get into.
Run this code without any problems, can write and read. But!! What if the key-value was written by another client? If I add key-value through redis-CLI tool, it will not be retrieved through cache.get(key), of course, the skey-value added by this code will not be retrieved through get on client.
The key-value added to this code is as follows:
[root@incisor ~]# / usr/local/redis/bin/redis - cli - h # 127.0.0.1 127.0.0.1, negligible - h parameter127.0.0.1:6379 > keys *# view all keys
1) ":1:skey"
Copy the code
. Cache.set (key, value) concatenates the string “:1:” before the key. That’s why I call this cache an invisible pit.
2) by get_redis_connection ()
from django_redis import get_redis_connection
from django.http import HttpResponse
def hello(request):
key = 'skey'
value = 'svalue'
conn = get_redis_connection('default')
conn.set(key, value)
if conn.get(key):
return HttpResponse('<h1>{0}: {1}</h1>'.format(key, conn.get(key)))
else:
return HttpResponse(' Not found
')
Copy the code
After executing, check the key value with redis-cli:
127.0.0.1:6379 > keys * 1)"skey"
Copy the code
Now the key is not concatenated, so I use this function a lot.
With get_redis_connection() it is best to set the decode_responses parameter in CACHES in settings.py to True, Also the ‘default’ in conn = get_redis_Connection (‘default’) is the ‘default’ for CACHES in settings.py.