1. 程式人生 > 實用技巧 >redis配置和使用:

redis配置和使用:

redis配置和使用:

CentOS7 :

因為本人使用的是華為雲伺服器,安裝教程在官網,所以安裝部分省略......

啟動redis:

redis-server

配置redis檔案:

# 首先先查詢redis.conf路徑
find / -name redis.conf
/etc/redis.conf

vim /etc/redis.conf
> 

命令模式下按 / 關鍵字  # 快速查詢關鍵字位置

# 配置遠端連線
# IF YOU ARE SURE YOU WANT YOUR INSTANCE TO LISTEN TO ALL THE INTERFACES
# JUST COMMENT THE FOLLOWING LINE.
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# bind 127.0.0.1
bind 0.0.0.0

# 保護模式開啟
# even if no authentication is configured, nor a specific set of interfaces
# are explicitly listed using the "bind" directive.
protected-mode yes

# 後臺執行 
# 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


# 設定密碼
# 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 密碼

# 儲存退出
esc
Shift + ; 
x
Enter

再次啟動redis:

redis-server /etc/redis.conf
redis-cli
127.0.0.1:6379> ping
(error) NOAUTH Authentication required.

127.0.0.1:6379> auth 密碼
OK
127.0.0.1:6379> ping
PONG
任務完成:ojbk --- 允許了遠端連線又設定了密碼。
接下來去雲伺服器開啟安全組,開放埠。
安全組放通後可以去專案中使用了。

專案資料快取到redis:

前提是要安裝好redis, 配置好redis, 啟動好redis.

安裝庫:
pip install django-redis
pip install django-redis-cache
專案中快取配置:

setting >

CACHES = {
	'default': {
		'BACKEND': "django_redis.cache.RedisCache", # 找庫
        # 資料庫+驅動 (資料庫和驅動同名時可省略)://使用者名稱:密碼@主機:埠/庫
        # "redis://password@公網IP:埠/1" 可連線到雲伺服器
		'LOCATION': "redis://127.0.0.1:6379/1",  # 本機連結
		'OPTIONS': {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
        }
	}
}

去redis中查詢資料:

# 登入
redis-cli
auth 密碼
ping

#進入到第一個庫
select 1
# 獲取所有資料 
keys *
"1"
"2"
"3"
# 查詢資料
get "1"