Home > Database > Redis > Redis: a powerful tool for building highly scalable systems

Redis: a powerful tool for building highly scalable systems

王林
Release: 2023-11-07 10:45:20
Original
751 people have browsed it

Redis: a powerful tool for building highly scalable systems

Redis: A powerful tool for building highly scalable systems, specific code examples are required

Redis is an open source in-memory data structure storage system that can also be used as a message queue and cache database, etc. It is a powerful tool that helps us build highly scalable systems. This article will introduce you to several common features of Redis and their implementation code.

  1. Sentinel Mode

Redis’s sentinel mode can help us achieve high availability. When the master node goes down, Sentinel can automatically elect a new master node. The following is a simple sentinel mode implementation example:

Configuration file:

sentinel monitor mymaster 127.0.0.1 6379 2
sentinel down-after-milliseconds mymaster 5000
sentinel failover-timeout mymaster 60000
Copy after login

Code:

# 使用redis-py实现哨兵模式
import redis

sentinel = redis.RedisSentinel(
    [('127.0.0.1', 26379)],
    socket_timeout=0.1,
)

redis_master = sentinel.master_for('mymaster', socket_timeout=0.1)
redis_slave = sentinel.slave_for('mymaster', socket_timeout=0.1)

redis_master.set('key', 'value')
print(redis_slave.get('key'))
Copy after login
  1. Distributed lock

In a distributed system, in order to avoid concurrency problems, we need to use distributed locks to control access to shared resources. Redis can implement distributed locks through SETNX and GETSET commands. The following is a simple Redis distributed lock implementation example:

Code:

import redis

class RedisLock(object):
    def __init__(self, name, acquire_timeout=10, expire_time=60):
        self.redis = redis.Redis()
        self.name = 'redis_lock_key_{}'.format(name)
        self.acquire_timeout = acquire_timeout
        self.expire_time = expire_time

    def acquire_lock(self):
        start_time = time.time()
        while True:
            end_time = time.time()
            if self.redis.setnx(self.name, 1):
                self.redis.expire(self.name, self.expire_time)
                return True
            elif end_time - start_time > self.acquire_timeout:
                return False
            time.sleep(0.1)

    def release_lock(self):
        self.redis.delete(self.name)
        
redis_lock = RedisLock('test')
if redis_lock.acquire_lock():
    try:
        # 操作共享资源
        pass
    finally:
        redis_lock.release_lock()
Copy after login
  1. Publish/Subscribe Mode

Redis’s publish/subscribe mode allows Different clients communicate in real time through a channel. The following is a simple publish/subscribe mode implementation example:

Code:

import redis
import threading

def subscribe_channel(redis, channel):
    pub_sub = redis.pubsub()
    pub_sub.subscribe(channel)
    for message in pub_sub.listen():
        print(message)

redis_sub = redis.StrictRedis(decode_responses=True)
redis_pub = redis.StrictRedis(decode_responses=True)

redis_thread = threading.Thread(target=subscribe_channel, args=(redis_sub, 'test_channel'))
redis_thread.start()

redis_pub.publish('test_channel', 'Hello, Redis!')
Copy after login
  1. Lua script

Redis supports complex implementations by executing Lua scripts Operations, which are atomic and can be executed efficiently in Redis. The following is a simple Lua script implementation example:

Code:

import redis

redis_client = redis.Redis()

add_script = redis_client.register_script("""
    local current_value = redis.call('get', KEYS[1])
    current_value = tonumber(current_value) or 0
    current_value = current_value + tonumber(ARGV[1])
    redis.call('set', KEYS[1], current_value)
    return current_value
""")

add_script(keys=['test_lua_key'], args=[1])
Copy after login

Summary

This article introduces four common features of Redis and provides corresponding code examples. Sentinel mode and distributed locks can help us achieve high availability and concurrency control; the publish/subscribe mode can help us achieve real-time communication; and Lua scripts can help us implement complex operations. By learning these features of Redis, we can better build highly scalable systems.

The above is the detailed content of Redis: a powerful tool for building highly scalable systems. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template