apt的包里自带redis,如果对redis的版本不是要求特别高的,可以直接使用apt进行安装:
apt install redis-server
启动redis:
redis-server
启动命令行接口:
redis-cli
注意:使用apt安装后,redis的默认配置文件的位置是:/etc/redis/redis.conf
复制配置文件后进行修改:
nano /etc/redis/redis.conf
注释掉bind ip这行,把保护模式关闭,外网就可以访问了(要设置密码):
#bind 127.0.0.1 ::1
protected-mode no #把yes改为no
apt安装的redis是默认后台启动的:
# By default Redis does not run as a daemon. Use 'yes' if you need it.
# Note that Redis will write a pid file in /var/run/redis.pid when daemonized.
daemonize yes
设置密码:
# Require clients to issue AUTH before processing any other
# commands. This might be useful in environments in which you do not trust
# others with access to the host running redis-server.
#
# This should stay commented out for backward compatibility and because most
# people do not need auth (e.g. they run their own servers).
#
# Warning: since Redis is pretty fast an outside user can try up to
# 150k passwords per second against a good box. This means that you should
# use a very strong password otherwise it will be very easy to break.
#
requirepass test
用新的配置文件重启redis:
service redis-server restart
修改配置:
sudo echo 'vm.overcommit_memory = 1' >> /etc/sysctl.conf
sudo sysctl -p
sudo echo 2048 > /proc/sys/net/core/somaxconn
sudo echo never > /sys/kernel/mm/transparent_hugepage/enabled
chmod 644 /etc/redis/redis.conf
service redis-server start
先安装redis库:
pip3 install redis
然后进行连接:
import redis
r=redis.Redis(host='127.0.0.1',port=6379,password='test')
r.set('test','connect success')
print(r.get('test'))
如果输出connect success,说明连接成功了。
需要注意的是redis.Redis的参数有以下这些:
__init__(self, host='localhost', port=6379, db=0, password=None, socket_timeout=None, socket_connect_timeout=None, socket_keepalive=None, socket_ke
epalive_options=None, connection_pool=None, unix_socket_path=None, encoding='utf-8', encoding_errors='strict', charset=None, errors=None, decode_respon
ses=False, retry_on_timeout=False, ssl=False, ssl_keyfile=None, ssl_certfile=None, ssl_cert_reqs='required', ssl_ca_certs=None, max_connections=None)
我的数据库系列文章: