A demo (Python version) that uses redis subscription and release for real-time monitoring)

Source: Internet
Author: User

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.