zoukankan      html  css  js  c++  java
  • redis + python 做消息队列

    redis卸载:后配安装https://blog.csdn.net/isea533/article/details/84550237

    一、使用redis的List类型结合lpush 和 brpop 来实现

    简介

    • 首先redis的List 相当于一个队列,可以实现先进先出的规则
    • 采用brpop 是因为当队列中没有的时候会进行阻塞,直到队列中有可弹出元素或者等待超时

    模拟问题:

    • 访问太多,服务器处理速度太慢,如果每隔用户等待,服务器反馈的话,时间太长,http连接超时,出现服务器错误。

    模拟实现过程:

    • 有一个客户端不断的往队列里放东西(数据),采用多线程,模拟大量用户访问的情况
    • 有一个服务器不断的从队列中取出打印,并设置每次打印时间睡2秒

    redis的List结构介绍

    key [value, value]
    key 代表List的名字, [value, ...] 是值
    

    客户client.py

    import random
    import threading
    import redis
    import config
    
    lock = threading.Lock()
    lock.acquire()
    lock.release()
    
    
    pool = redis.ConnectionPool(host=config.HOST, port=config.PORT, 
                                decode_responses=True, password=config.PASSWORD)
    
    r = redis.Redis(connection_pool=pool)
    
    # 客户往redis 中放数据
    def fun1(redisObj):
        value = random.randint(0, 100)
        # 往ccc列表中存放
        print("开始发送数据:", value)
        redisObj.lpush("print",str(value))
    
    for i in range(100):
        threading.Thread(target=fun1, args=(r,)).start()
    

    服务器server.py

    import redis
    import time
    import config
    
    
    pool = redis.ConnectionPool(host=config.HOST, port=config.PORT, decode_responses=True, password=config.PASSWORD)
    r = redis.Redis(connection_pool=pool)
    # 服务端不断的取
    while True:
        value = r.brpop("print")
        time.sleep(2)
        print(value)
    

    问题回顾

    我们之前说存在阻塞太久断开连接的问题,解决下

    方式: 将连接作为一个函数,进行错误捕捉,发生问题的时候重新连接。

    import redis
    import time
    import config
    
    def get_redis():
        pool = redis.ConnectionPool(host=config.HOST, port=config.PORT, decode_responses=True, password=config.PASSWORD)
        r = redis.Redis(connection_pool=pool)
        return r
    # 服务端不断的取
    r = get_redis()
        
    while True:
        try:
            value = r.brpop("print")
            time.sleep(2)
            print(value)
        except Exception as e:
            print("等待超时重连")
            r = get_redis()
    

    结果:

    问题,业务从List中取出了值,但是业务线崩溃了,重启业务服务后,这个条数据是不是就丢失了?怎么解决

  • 相关阅读:
    springboot+maven+thymeleaf配置实战demo
    报错AbstractStandardExpressionAttributeTagProcessor
    IllegalStateException: Unable to find a @SpringBootConfiguration
    Java装饰模式
    Java容器类解析
    jdk之object源码理解
    osx brew mysql
    java String[] 初始化
    date 常用
    mac mysql
  • 原文地址:https://www.cnblogs.com/ShanCe/p/14663870.html
Copyright © 2011-2022 走看看