Sử dụng Python để làm việc với Memcached, Redis, RabbitMQ và SQLAlchemy

Memcached là hệ thống bộ nhớ đệm phân tán hiệu suất cao, giúp giảm tải cho cơ sở dữ liệu trong các ứng dụng web động. Nó lưu trữ dữ liệu dưới dạng cặp key-value trong bộ nhớ, từ đó giảm số lần truy vấn trực tiếp vào database.

Cài đặt và cấu hình Memcached

# Cài gói phụ thuộc
yum install libevent-devel

# Cài Memcached
yum -y install memcached

# Khởi động dịch vụ
/usr/bin/memcached -d -u root -l 192.168.7.102 -m 1024 -p 11211

Kết nối và kiểm tra qua Telnet

telnet 192.168.7.102 11211
# Sau khi kết nối thành công, có thể dùng lệnh:
# set, get, delete, stats...

Sử dụng Python với Memcached

# Cài thư viện Python
pip install python-memcached

# Ví dụ sử dụng
import memcache

client = memcache.Client(['192.168.7.102:11211'], debug=True)
client.set("user_id", "12345")
value = client.get("user_id")
print(value)  # Output: 12345

Redis – Hệ thống lưu trữ key-value linh hoạt hơn

Redis hỗ trợ nhiều kiểu dữ liệu như string, list, set, hash, sorted set và cung cấp tính năng bền vững (persistence) cùng cơ chế master-slave replication.

Cài đặt Redis

# Kiểm tra và cài GCC nếu chưa có
yum -y install gcc

# Tải và biên dịch Redis
cd /opt/
wget http://download.redis.io/releases/redis-7.0.0.tar.gz
tar xzf redis-7.0.0.tar.gz
cd redis-7.0.0
make && make install

# Cấu hình chạy nền
cp redis.conf /etc/redis.conf
sed -i 's/daemonize no/daemonize yes/' /etc/redis.conf

Lệnh cơ bản trong Redis CLI

SET user:name "Alice"
GET user:name
EXISTS user:name
DEL user:name
KEYS *
TYPE user:name

Python thao tác với Redis

pip install redis

import redis

# Kết nối đơn giản
r = redis.Redis(host='localhost', port=6379, db=0)
r.set('session:token', 'abc123xyz')
print(r.get('session:token'))

# Sử dụng Connection Pool
pool = redis.ConnectionPool(host='localhost', port=6379, db=0)
r_pool = redis.Redis(connection_pool=pool)

# Pipeline để thực thi nhiều lệnh atomically
pipe = r_pool.pipeline()
pipe.set('counter', 1)
pipe.incr('counter')
pipe.get('counter')
results = pipe.execute()  # Trả về danh sách kết quả

Xuất bản và đăng ký (Pub/Sub)

class RedisChannel:
    def __init__(self, host='localhost', port=6379, channel='events'):
        self.conn = redis.Redis(host=host, port=port)
        self.channel = channel

    def publish(self, message):
        self.conn.publish(self.channel, message)

    def subscribe(self):
        pubsub = self.conn.pubsub()
        pubsub.subscribe(self.channel)
        return pubsub

# Publisher
pub = RedisChannel()
pub.publish("System started")

# Subscriber
sub = RedisChannel().subscribe()
for msg in sub.listen():
    if msg['type'] == 'message':
        print("Received:", msg['data'])

RabbitMQ – Hệ thống hàng đợi tin nhắn doanh nghiệp

RabbitMQ triển khai giao thức AMQP, cho phép các ứng dụng giao tiếp không đồng bộ thông qua hàng đợi tin nhắn.

Cài đặt RabbitMQ

# Thêm repo EPEL
rpm -ivh https://dl.fedoraproject.org/pub/epel/epel-release-latest-8.noarch.rpm

# Cài Erlang và RabbitMQ
yum -y install erlang rabbitmq-server

# Khởi động dịch vụ
systemctl start rabbitmq-server
systemctl enable rabbitmq-server

Python làm việc với RabbitMQ

pip install pika

import pika

# Kết nối và gửi tin nhắn
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()

channel.queue_declare(queue='task_queue')

channel.basic_publish(
    exchange='',
    routing_key='task_queue',
    body='Hello Worker!',
    properties=pika.BasicProperties(delivery_mode=2)  # persistent
)

print(" [x] Sent 'Hello Worker!'")
connection.close()

Mô hình Consumer

def callback(ch, method, properties, body):
    print(f" [x] Received {body.decode()}")
    ch.basic_ack(delivery_tag=method.delivery_tag)

channel.basic_consume(queue='task_queue', on_message_callback=callback)
channel.start_consuming()

Thẻ: python memcached Redis rabbitmq pika

Đăng vào ngày 18 tháng 5 lúc 23:15