Redis's list type has a good feature, that is, the length of the current list will be returned after each element is added. With this feature, we can monitor its length, for example, our key is the IP address registered by the user, and the list stores the ID of the user already registered on this IP address. When the number of users exceeds 1000, an alarm is triggered, the subscription and release functions of redis help you easily implement the Notification monitoring program.
Step 1: download the required software:
Redis: http://redis.googlecode.com/files/redis-2.6.14.tar.gz
Redis-py: https://github.com/andymccurdy/redis-py/archive/master.zip
Step 2: write client. py:
#! /Usr/bin/ENV Python
# Coding = UTF-8
Import redis
If _ name _ = "_ main __":
Rc = redis. redis (host = '10. 250.2.18 ', Port = 6379, DB = 0, password = 'master123 ')
Ip_addr = "192.168.1.100"
For I in xrange (500 ):
Count = RC. lpush ("IP: 192.168.1.100", I)
If count> 1000:
RC. Publish ("count_alarm", count)
RC. Publish ('IP _ alarm ', ip_addr)
If no redis password is set, you can delete the Password attribute [not configured by default]
Step 3: Write server. py:
#! /Usr/bin/ENV Python
# Coding = UTF-8
Import redis
Rc = redis. redis (host = '10. 250.2.18 ', Port = 6379, DB = 0, password = 'master123 ')
PS = RC. pubsub ()
PS. subscribe (['count _ alarm ', 'IP _ alarm']) # subscribe to two channels: count_alarm ip_alarm
For item in PS. Listen ():
If item ['type'] = 'message ':
Print item ['channel'], item ['data'] # monitoring-related tasks can be done here, such as email notification, SMS notification, or IM notification.
Step 4: view the effect
Run server. py:
Python server. py
Run client. py:
Python client. py
Client. py will end immediately, and server. py will listen all the time, and a simple demo will be ready.