redis的python使用

windows下安装使用

今天做一个练习需要用到python的redis模块,但安装了redis模块后,运行脚本却得到这样的结果:

PS H:\project\python course\python_pra> python producer.py
生产者生产了两个数字:3, 95
Exception in thread Thread-1:
Traceback (most recent call last):
  File "D:\Python39\lib\site-packages\redis\connection.py", line 567, in connect
    sock = self._connect()
  File "D:\Python39\lib\site-packages\redis\connection.py", line 625, in _connect
    raise err
  File "D:\Python39\lib\site-packages\redis\connection.py", line 613, in _connect
    sock.connect(socket_address)
ConnectionRefusedError: [WinError 10061] 由于目标计算机积极拒绝,无法连接。

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "D:\Python39\lib\threading.py", line 954, in _bootstrap_inner
    self.run()
  File "H:\project\python course\python_pra\producer.py", line 17, in run
    self.queue.rpush('producer', json.dumps((a, b)))
  File "D:\Python39\lib\site-packages\redis\commands\core.py", line 1809, in rpush
    return self.execute_command('RPUSH', name, *values)
  File "D:\Python39\lib\site-packages\redis\client.py", line 1068, in execute_command
    conn = self.connection or pool.get_connection(command_name, **options)
  File "D:\Python39\lib\site-packages\redis\connection.py", line 1173, in get_connection
    connection.connect()
  File "D:\Python39\lib\site-packages\redis\connection.py", line 571, in connect
    raise ConnectionError(self._error_message(e))
redis.exceptions.ConnectionError: Error 10061 connecting to localhost:6379. 由于目标计算机积极拒绝,无法连接。.

很长啊,啪的一下,就那么长了,这里主要是说,本机的redis服务没有启动,而我的电脑还么安装redis,所以现在先安装redis。
安装网址
需要注意的是,这里的网址是用的github进行管理,所以访问会很慢甚至断掉,具体方法大家百度即可,很简单的。
点进去下载压缩包即可
在这里插入图片描述
然后解压缩在你需要安装的目录,然后我们来看看能不能启动redis服务

./redis-server redis.windows.conf

对应目录输入该命令,出现以下界面就表明redis服务已启动;如果是使用的安装包,那就是已经配置了redis服务和环境变量,但一些客户端的使用如redis-cli命令的使用还需配置环境,简单做法就是把安装目录添加进环境变量path中即可。

在这里插入图片描述
接下来我们先看看我们的代码是否可用了,测试代码是一个生产者一个消费者,
producer.py如下:

import time
import json
import redis
import random
from threading import Thread

class Producer(Thread):
	def __init__(self):
		super().__init__()
		self.queue = redis.Redis()

	def run(self):
		while True:
			a = random.randint(0, 10)
			b = random.randint(90, 100)
			print(f'生产者生产了两个数字: {
      
      a}, {
      
      b}')
			self.queue.rpush('producer', json.dumps((a, b)))
			time.sleep(2)

producer = Producer()
producer.start()
while True:
	time.sleep(1)

consumer.py如下:

import json
import time
import redis
import random
from threading import Thread

class Consumer(Thread):
	def __init__(self):
		super().__init__()
		self.queue = redis.Redis()

	def run(self):
		while True:
			num = self.queue.blpop('producer')
			a, b = json.loads(num[1].decode())
			print(f'消费者消费了一组数,{
      
      a} + {
      
      b} = {
      
      a + b}')
			time.sleep(random.randint(0, 10))

consumer = Consumer()
consumer.start()
while True:
	time.sleep(1)

测试结果如下:
在这里插入图片描述
嗯,很流畅。那么接下来呢?结束啦?不是哦,你的redis服务现在是属于软件点击启动才启动,但我们每次使用redis模块都要到该目录下输入命令启动一次?太麻烦了,我们设置一下让它在电脑中跟随其他服务启动而启动。
同样是该目录下输入以下命令

PS D:\Redis-x64-3.2.100> ./redis-server --service-install redis.windows.conf --loglevel verbose
[11896] 04 Dec 17:39:05.607 # HandleServiceCommands: system error caught. error code=1073, message = CreateService failed: unknown error

PS D:\Redis-x64-3.2.100>

嗯。。。。。。失败了,为什么呢?
查了一下,它说之前已经安装了,所以启动同样的命令失败,嗯?所以我关闭了也算是服务在后台?我不确定,现在也不检验这个东西,那我们就先卸载一下然后在启动吧

PS D:\Redis-x64-3.2.100> ./redis-server --service-uninstall
[10332] 04 Dec 17:41:15.503 # Redis service successfully uninstalled.
PS D:\Redis-x64-3.2.100> ./redis-server --service-install redis.windows.conf --loglevel verbose
[1884] 04 Dec 17:42:04.596 # Granting read/write access to 'NT AUTHORITY\NetworkService' on: "D:\Redis-x64-3.2.100" "D:\Redis-x64-3.2.100\"
[1884] 04 Dec 17:42:04.596 # Redis successfully installed as a service.
PS D:\Redis-x64-3.2.100> ./redis-server --service-start
[13984] 04 Dec 17:42:41.424 # Redis service successfully started.
PS D:\Redis-x64-3.2.100>

然后我关闭了cmd终端,试验一下可行性
在这里插入图片描述
嗯,可以。哈哈哈。redis作为一个非关系型数据库里面的键值数据库代表,适合做高速缓存,可以做队列,上面的例子就是使用redis作为队列中间件,从而使得我们可以在执行生产者-消费者任务的时候,得以在不中断任务的同时,对队列情况进行查看,如:

PS C:\Users\samu\Desktop> redis-cli
127.0.0.1:6379> llen producer
(integer) 189
127.0.0.1:6379> lrange producer 0 30
 1) "[6, 90]"
 2) "[0, 96]"
 3) "[9, 98]"
 4) "[10, 99]"
 5) "[3, 94]"
 6) "[2, 90]"
 7) "[2, 96]"
 8) "[9, 100]"
 9) "[3, 94]"
10) "[7, 99]"
11) "[0, 98]"
12) "[9, 97]"
13) "[8, 96]"
14) "[7, 100]"
15) "[1, 94]"
16) "[4, 95]"
17) "[0, 92]"
18) "[7, 92]"
19) "[5, 90]"
20) "[5, 94]"
21) "[3, 91]"
22) "[2, 92]"
23) "[5, 100]"
24) "[3, 91]"
25) "[2, 95]"
26) "[1, 90]"
27) "[7, 90]"
28) "[10, 98]"
29) "[9, 94]"
30) "[9, 95]"
31) "[3, 99]"
127.0.0.1:6379>

如上所示,使用redis客户端登陆后,对于当前redis可以使用llen命令查看对应队列的数据量,lrange可以迭代参数指示区间内对应队列的并输出,更多内容可以查看菜鸟教程中的redis数据库内容,比较简易好上手。

linux的centos7云服务器安装使用

在windows系统中已经尝试过了,那linux环境呢?下面是我的腾讯服务器的实验,腾讯服务器装载的是centos7系统,它已经内置了python,所以我先安装了pip管理。

yum install python-pip

然后安装redis模块

pip install redis

但却出现以下错误:

 Downloading http://mirrors.tencentyun.com/pypi/packages/da/f6/c83229dcc3635cdeb51874184241a9508ada15d8baa337a41093fab58011/pip-21.3.1.tar.gz (1.7MB)
    100% |████████████████████████████████| 1.7MB 3.3MB/s 
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/tmp/pip-build-VjaPWF/pip/setup.py", line 7
        def read(rel_path: str) -> str:
                         ^
    SyntaxError: invalid syntax
    
    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-VjaPWF/pip/

查了一下,资料显示是我的python版本太老了,不支持该模块,所以要安装一下python3,然后安装redis,这里要用pip3

yum install python3
pip3 install redis

然后我们的模块都备全了,要开启一下服务。

redis-server

在这里插入图片描述
然后运行一下程序即可,注意之前是安装了python3,所以运行也得是它

[root@VM-0-17-centos ~]# python3 producer.py
生产者生产了两个数字:{
    
    a},{
    
    b}
生产者生产了两个数字:{
    
    a},{
    
    b}
生产者生产了两个数字:{
    
    a},{
    
    b}
生产者生产了两个数字:{
    
    a},{
    
    b}
生产者生产了两个数字:{
    
    a},{
    
    b}
生产者生产了两个数字:{
    
    a},{
    
    b}
^Z
[2]+  Stopped                 python3 producer.py

结果如上所示,可用,这里只是进行一下简单的使用,所以linux中的服务启动等就不继续了。
不过redis的启动在win11的ubuntu子系统上出错

457:M 04 Dec 2021 21:34:20.401 # Server initialized
457:M 04 Dec 2021 21:34:20.401 # WARNING overcommit_memory is set to 0! Background save may fail under low memory condition. To fix this issue add 'vm.overcommit_memory = 1' to /etc/sysctl.conf and then reboot or run the command 'sysctl vm.overcommit_memory=1' for this to take effect.
457:M 04 Dec 2021 21:34:20.402 # WARNING you have Transparent Huge Pages (THP) support enabled in your kernel. This will create latency and memory usage issues with Redis. To fix this issue run the command 'echo never > /sys/kernel/mm/transparent_hugepage/enabled' as root, and add it to your /etc/rc.local in order to retain the setting after a reboot. Redis must be restarted after THP is disabled.
457:M 04 Dec 2021 21:34:20.404 * Ready to accept connections

这里先做个记录吧,不进行了。

redis的pthon应用踩了个坑

尝试了redis的windows安装包,挺ok,不过有一些命令的使用依然需要把redis的安装目录配置到环境变量中,这个重说一下。另外就是由于根据网上一些教程的使用,给redis数据库配置了密码(记事本打开redis安装目录下redis.windows-service.conf文件):

# requirepass foobared

找到上面位置添加requirepass 123456以后就配置了当地redis数据库的访问密码是123456,导致python使用时报错:

PS C:\Users\samu\Desktop\python练习> python producer.py
生产者生产了两个数字: 10, 96
Exception in thread Thread-1:
Traceback (most recent call last):
  File "D:\Python39\lib\threading.py", line 954, in _bootstrap_inner
    self.run()
  File "C:\Users\samu\Desktop\python练习\producer.py", line 17, in run
    self.queue.rpush('producer', json.dumps((a, b)))
  File "D:\Python39\lib\site-packages\redis\commands\core.py", line 1809, in rpush
    return self.execute_command('RPUSH', name, *values)
  File "D:\Python39\lib\site-packages\redis\client.py", line 1071, in execute_command
    return conn.retry.call_with_retry(
  File "D:\Python39\lib\site-packages\redis\retry.py", line 35, in call_with_retry
    fail(error)
  File "D:\Python39\lib\site-packages\redis\client.py", line 1076, in <lambda>
    lambda error: self._disconnect_raise(conn, error))
  File "D:\Python39\lib\site-packages\redis\client.py", line 1061, in _disconnect_raise
    raise error
  File "D:\Python39\lib\site-packages\redis\retry.py", line 32, in call_with_retry
    return do()
  File "D:\Python39\lib\site-packages\redis\client.py", line 1072, in <lambda>
    lambda: self._send_command_parse_response(conn,
  File "D:\Python39\lib\site-packages\redis\client.py", line 1051, in _send_command_parse_response
    return self.parse_response(conn, command_name, **options)
  File "D:\Python39\lib\site-packages\redis\client.py", line 1084, in parse_response
    response = connection.read_response()
  File "D:\Python39\lib\site-packages\redis\connection.py", line 748, in read_response
    response = self._parser.read_response()
  File "D:\Python39\lib\site-packages\redis\connection.py", line 334, in read_response
    raise error
redis.exceptions.AuthenticationError: Authentication required.

由于我之前是用的c/c++,所以看python运行报错一时半会还不会看,其实直接看最后一条即可,上面redis.exceptions.AuthenticationError: Authentication required.说redis的使用需要认证,简单来说就是我上面的代码是默许作为客户端的使用是不设密码的,然后就gg了,所以我们可以取消掉123456密码:

PS C:\Users\samu\Desktop> redis-cli
127.0.0.1:6379> auth 123456
OK
127.0.0.1:6379> config set requirepass ''
OK
127.0.0.1:6379>

如此即可,不过由于密码是写进设置文本中的,我不确定是否重启后在客户端的设置是否依然生效,先试一下。嗯,重启后重新运行上面producer.py脚本,同样的错误,所以还是把设置文件中添加的内容删掉吧。不过这里我又踩了个坑,就是我没有停止redis服务就命令卸载了,然后重新安装的时候报错了:

PS D:\Redis> redis-server --service-install
[6464] 13 Feb 23:33:42.070 # HandleServiceCommands: system error caught. error code=1072, message = CreateService failed: 指定的服务已标记为删除。

简单方法就是停了服务,卸载服务,重新安装服务

PS D:\Redis> redis-server --service-stop
[8420] 13 Feb 23:41:01.322 # Redis service successfully stopped.
PS D:\Redis> redis-server --service-uninstall
[3084] 13 Feb 23:41:43.528 # Redis service successfully uninstalled.
PS D:\Redis> redis-server --service-install redis.windows.conf
[2732] 13 Feb 23:43:26.959 # Granting read/write access to 'NT AUTHORITY\NetworkService' on: "D:\Redis" "D:\Redis\"
[2732] 13 Feb 23:43:26.961 # Redis successfully installed as a service.

如果你运行producer.py还是报错,而且报以下的错:

redis.exceptions.ConnectionError: Error 10061 connecting to localhost:6379. 由于目标计算机积极拒绝,无法连接。.

那就是你的redis服务没开启,启动了就好,我这里是直接在[计算机管理]-[服务]-[Redis]中启动的,当然也可以命令启动:

redis-server --service-start

接下来就很顺当了,为了试验,又重启了一下再运行producer.py也是没问题的。redis还有其他合适的应用场景,这里重点学习了队列中间件的应用,其他的大家可以自己对应查找一下,这里不做拓展。

猜你喜欢

转载自blog.csdn.net/weixin_44948269/article/details/121717979