📃
Python Reference
  • Installation
  • First Steps
  • Variables
  • Operators and Expressions
  • Control Flow
  • Loops
  • Functions
  • String
  • List
  • Dictionany
  • Modules
  • Class
  • File
  • Folder
  • Module os
  • Image
  • JSON
  • XML
  • Connection MySQL
  • Connection Redis
  • Connection Memcached
  • Connection RabbitMQ
  • Restful client
  • STMP
  • Socket
Powered by GitBook
On this page
  • Cài đặt
  • Kết nối đến Redis
  • Thực hiện lệnh
  • Pipeline
  • Follower me

Was this helpful?

Connection Redis

PreviousConnection MySQLNextConnection Memcached

Last updated 4 years ago

Was this helpful?

Redis là một memory cache server hỗ trợ persistant data thông dụng nhất hiện nay. Nội dung chương này sẽ hướng dẫn bạn kết nối đến một Redis server (đã được cài đặt sẵn) thông qua thư viện redis-py.

Cài đặt

Có thể xem thêm về hướng dẫn cài đặt thư viện này tại

Đơn giản cài thông qua pip là:

$ sudo pip install redis

Kết nối đến Redis

Để kết nối đến Redis server thì bạn có thể xem ví dụ sau:

import redis

r = redis.StrictRedis(host = 'localhost', port = 6379, db = 0)

Thực hiện lệnh

Thực hiện các lệnh bình thường trên đối tượng redis.

Ví dụ:

import redis

r = redis.StrictRedis(...)
r.set('foo', 'bar')
print r.get('foo')
# Hiển thị 'bar'

Pipeline

Pipeline là kỹ thuật được dùng trong trường hợp bạn muốn tăng performance bởi gộp nhiều lệnh vào một request thay vì mỗi lệnh là một request như thông thường. Xem ví dụ sau để hiểu cách sử dụng pipeline bằng redis-py:

import redis

r = redis.StrictRedis(...)
r.set('foo', 'bar')
pipe = r.pipeline()
pipe.set('a', 1)
pipe.set('b', 2)
pipe.set('c', 3)
pipe.get('foo')
pipe.execute()

Sau khi gọi phương thức execute() thì sẽ trả về List tương ứng với các kết quả của từng lệnh. Ví dụ kết quả từ đoạn code trên:

[True, True, True, 'bar']

Follower me

Facebook:

Blog:

Github:

https://github.com/andymccurdy/redis-py
https://www.facebook.com/lamsaodecode
https://lamsaodecode.blogspot.com
https://lamsaodecode.github.io/introduction