Bu sayfa henüz yerel dilinizde mevcut değildir. Daha fazla dil seçeneği eklemek için yoğun bir şekilde çalışıyoruz. Desteğiniz için teşekkür ederiz.

Compute
Elastic Cloud Server
Huawei Cloud Flexus
Bare Metal Server
Auto Scaling
Image Management Service
Dedicated Host
FunctionGraph
Cloud Phone Host
Huawei Cloud EulerOS
Networking
Virtual Private Cloud
Elastic IP
Elastic Load Balance
NAT Gateway
Direct Connect
Virtual Private Network
VPC Endpoint
Cloud Connect
Enterprise Router
Enterprise Switch
Global Accelerator
Management & Governance
Cloud Eye
Identity and Access Management
Cloud Trace Service
Resource Formation Service
Tag Management Service
Log Tank Service
Config
OneAccess
Resource Access Manager
Simple Message Notification
Application Performance Management
Application Operations Management
Organizations
Optimization Advisor
IAM Identity Center
Cloud Operations Center
Resource Governance Center
Migration
Server Migration Service
Object Storage Migration Service
Cloud Data Migration
Migration Center
Cloud Ecosystem
KooGallery
Partner Center
User Support
My Account
Billing Center
Cost Center
Resource Center
Enterprise Management
Service Tickets
HUAWEI CLOUD (International) FAQs
ICP Filing
Support Plans
My Credentials
Customer Operation Capabilities
Partner Support Plans
Professional Services
Analytics
MapReduce Service
Data Lake Insight
CloudTable Service
Cloud Search Service
Data Lake Visualization
Data Ingestion Service
GaussDB(DWS)
DataArts Studio
Data Lake Factory
DataArts Lake Formation
IoT
IoT Device Access
Others
Product Pricing Details
System Permissions
Console Quick Start
Common FAQs
Instructions for Associating with a HUAWEI CLOUD Partner
Message Center
Security & Compliance
Security Technologies and Applications
Web Application Firewall
Host Security Service
Cloud Firewall
SecMaster
Anti-DDoS Service
Data Encryption Workshop
Database Security Service
Cloud Bastion Host
Data Security Center
Cloud Certificate Manager
Edge Security
Situation Awareness
Managed Threat Detection
Blockchain
Blockchain Service
Web3 Node Engine Service
Media Services
Media Processing Center
Video On Demand
Live
SparkRTC
MetaStudio
Storage
Object Storage Service
Elastic Volume Service
Cloud Backup and Recovery
Storage Disaster Recovery Service
Scalable File Service Turbo
Scalable File Service
Volume Backup Service
Cloud Server Backup Service
Data Express Service
Dedicated Distributed Storage Service
Containers
Cloud Container Engine
Software Repository for Container
Application Service Mesh
Ubiquitous Cloud Native Service
Cloud Container Instance
Databases
Relational Database Service
Document Database Service
Data Admin Service
Data Replication Service
GeminiDB
GaussDB
Distributed Database Middleware
Database and Application Migration UGO
TaurusDB
Middleware
Distributed Cache Service
API Gateway
Distributed Message Service for Kafka
Distributed Message Service for RabbitMQ
Distributed Message Service for RocketMQ
Cloud Service Engine
Multi-Site High Availability Service
EventGrid
Dedicated Cloud
Dedicated Computing Cluster
Business Applications
Workspace
ROMA Connect
Message & SMS
Domain Name Service
Edge Data Center Management
Meeting
AI
Face Recognition Service
Graph Engine Service
Content Moderation
Image Recognition
Optical Character Recognition
ModelArts
ImageSearch
Conversational Bot Service
Speech Interaction Service
Huawei HiLens
Video Intelligent Analysis Service
Developer Tools
SDK Developer Guide
API Request Signing Guide
Terraform
Koo Command Line Interface
Content Delivery & Edge Computing
Content Delivery Network
Intelligent EdgeFabric
CloudPond
Intelligent EdgeCloud
Solutions
SAP Cloud
High Performance Computing
Developer Services
ServiceStage
CodeArts
CodeArts PerfTest
CodeArts Req
CodeArts Pipeline
CodeArts Build
CodeArts Deploy
CodeArts Artifact
CodeArts TestPlan
CodeArts Check
CodeArts Repo
Cloud Application Engine
MacroVerse aPaaS
KooMessage
KooPhone
KooDrive
On this page
Help Center/ Distributed Cache Service/ Best Practices/ Service Application/ Serializing Access to Frequently Accessed Resources

Serializing Access to Frequently Accessed Resources

Updated on 2024-12-31 GMT+08:00

Overview

Application Scenario

In monolithic deployment, you can use Java concurrency APIs such as ReentrantLock or synchronized to implement mutual exclusion locks. This native lock mechanism provided by Java ensures that multiple threads within a Java VM process are executed concurrently and sequentially.

However, this mechanism may fail in multi-node deployment because a node's lock only takes effect on threads in the Java VM where the node runs. For example, the concurrency level in Internet seckills requires multiple nodes to run at the same time. Assume that requests of two users arrive simultaneously on two nodes. Although the requests can be processed simultaneously on the respective nodes, an inventory oversold problem may still occur because the nodes use different locks.

Solution

To serialize access to resources, ensure that all nodes use the same lock. This requires a distributed lock.

The idea of a distributed lock is to provide a globally unique "thing" for different systems to allocate locks. When a system needs a lock, it asks the "thing" for a lock. In this way, different systems can obtain the same lock.

Currently, a distributed lock can be implemented using cache databases, disk databases, or ZooKeeper.

Implementing distributed locks using DCS Redis instances has the following advantages:

  • Simple operation: Locks can be acquired and released by using simple commands such as SET, GET, and DEL.
  • High performance: Cache databases deliver higher read/write performance than disk databases and ZooKeeper.
  • High reliability: DCS supports both master/standby and cluster instances, preventing single points of failure.

Implementing locks on distributed applications can avoid inventory oversold problems and nonsequential access. The following describes how to implement locks on distributed applications with Redis.

Prerequisites

  • A DCS instance has been created, and is in the Running state.
  • The network between the client server and the DCS instance is connected:
    • When the client and the DCS Redis instance are in the same VPC:

      By default, networks in a VPC can communicate with each other.

    • When the client and the DCS Redis instance are in different VPCs in the same region:

      If the client and DCS Redis instance are not in the same VPC, connect them by establishing a VPC peering connection. For details, see Does DCS Support Cross-VPC Access?

    • To access a Redis instance of another region on a client

      If the client server and the Redis instance are not in the same region, connect the network using Direct Connect. For details, see What Is Direct Connect.

    • For public access

      For details about how to access a DCS Redis 4.0/5.0/6.0 instance on a client over a public network, see Using Nginx for Public Access to DCS or Using ELB for Public Access to DCS.

  • You have installed JDK1.8 (or later) and a development tool (Eclipse is used as an example) on the client server, and downloaded the Jedis client.

    The development tools and clients mentioned in this document are for example only.

Procedure

  1. Run Eclipse on the server and create a Java project. Then, create a distributed lock implementation class DistributedLock.java and a test class CaseTest.java for the example code, and reference the Jedis client as a library to the project.

    Sample code of DistributedLock.java:

    package dcsDemo01;
    
    import java.util.UUID;
    
    import redis.clients.jedis.Jedis;
    import redis.clients.jedis.params.SetParams;
    
    public class DistributedLock {
        // Address and port for connecting to the Redis instance. Replace them with the actual values. 
        private final String host = "192.168.0.220";
        private final int port = 6379;
    
        private static final String SUCCESS = "OK";
    
        public  DistributedLock(){}
    
        /*
         * @param lockName      Lock name
         * @param timeout       Timeout for acquiring locks
         * @param lockTimeout   Validity period of locks
         * @return              Lock ID
         */
        public String getLockWithTimeout(String lockName, long timeout, long lockTimeout) {
            String ret = null;
            Jedis jedisClient = new Jedis(host, port);
    
            try {
                // Password for connecting to the Redis instance. Replace it with the actual value.
                String authMsg = jedisClient.auth("passwd");
                if (!SUCCESS.equals(authMsg)) {
                    System.out.println("AUTH FAILED: " + authMsg);
                }
    
                String identifier = UUID.randomUUID().toString();
                String lockKey = "DLock:" + lockName;
                long end = System.currentTimeMillis() + timeout;
    
                SetParams setParams = new SetParams();
                setParams.nx().px(lockTimeout);
    
                while(System.currentTimeMillis() < end) {
                    String result = jedisClient.set(lockKey, identifier, setParams);
                    if(SUCCESS.equals(result)) {
                        ret = identifier;
                        break;
                    }
    
                    try {
                        Thread.sleep(2);
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                    }
                }
            }
            catch (Exception e) {
                e.printStackTrace();
            }finally {
                jedisClient.quit();
                jedisClient.close();
            }
    
            return ret;
        }
    
        /*
         * @param lockName        Lock name
         * @param identifier    Lock ID
         */
        public void releaseLock(String lockName, String identifier) {
            Jedis jedisClient = new Jedis(host, port);
    
            try {
                String authMsg = jedisClient.auth("passwd");
                if (!SUCCESS.equals(authMsg)) {
                    System.out.println("AUTH FAILED: " + authMsg);
                }
    
                String lockKey = "DLock:" + lockName;
                if(identifier.equals(jedisClient.get(lockKey))) {
                    jedisClient.del(lockKey);
                }
            }
            catch (Exception e) {
                e.printStackTrace();
            }finally {
                jedisClient.quit();
                jedisClient.close();
            }
        }
    }
    NOTICE:

    The code only shows how DCS implements access control using locks. During actual implementation, deadlock and lock check also need to be considered.

    Assume that 20 threads are used to seckill ten Mate 10 mobile phones. The content of the test class CaseTest.java is as follows:
    package dcsDemo01;
    import java.util.UUID;
    
    public class CaseTest {
        public static void main(String[] args) {
            ServiceOrder service = new ServiceOrder();
            for (int i = 0; i < 20; i++) {
                ThreadBuy client = new ThreadBuy(service);
                client.start();
            }
        }
    }
    
    class ServiceOrder {
        private final int MAX = 10;
    
        DistributedLock DLock = new DistributedLock();
    
        int n = 10;
    
        public void handleOder() {
            String userName = UUID.randomUUID().toString().substring(0,8) + Thread.currentThread().getName();
            String identifier = DLock.getLockWithTimeout("Mate 10", 10000, 2000);
            System.out.println("Processing order for user " + userName + "");
            if(n > 0) {
                int num = MAX - n + 1;
                System.out.println("User "+ userName + " is allocated number " + num + " mobile phone. Number of mobile phones left: " + (--n) + "");
            }else {
                System.out.println("User "+ userName + " order failed.");
            }
            DLock.releaseLock("Mate 10", identifier);
        }
    }
    
    class ThreadBuy extends Thread {
        private ServiceOrder service;
    
        public ThreadBuy(ServiceOrder service) {
            this.service = service;
        }
    
        @Override
        public void run() {
            service.handleOder();
        }
    }

  2. Configure the connection address, port number, and password of the DCS instance in the example code file DistributedLock.java.

    In DistributedLock.java, set host and port to the connection address and port number of the instance. In the getLockWithTimeout and releaseLock methods, set passwd to the instance access password.

  3. Comment out the lock part in the test class CaseTest. The following is an example:

    //The lock code is commented out in the test class:
    public void handleOder() {
        String userName = UUID.randomUUID().toString().substring(0,8) + Thread.currentThread().getName();
        //Lock code
        //String identifier = DLock.getLockWithTimeout("Mate 10", 10000, 2000);
        System.out.println("Processing order for user " + userName + "");
        if(n > 0) {
            int num = MAX - n + 1;
                System.out.println("User "+ userName + " is allocated number " + num + " mobile phone. Number of mobile phones left: " + (--n) + "");
        }else {
                System.out.println("User "+ userName + " order failed.");
        }
        //Lock code
        //DLock.releaseLock("Mate 10", identifier);
    }

  4. Compile and run a lock-free class. The purchases are disordered, as shown in the following:

    Processing order for user e04934ddThread-5
    Processing order for user a4554180Thread-0
    User a4554180Thread-0 is allocated number 2 mobile phone. Number of mobile phones left: 8.
    Processing order for user b58eb811Thread-10
    User b58eb811Thread-10 is allocated number 3 mobile phone. Number of mobile phones left: 7.
    Processing order for user e8391c0eThread-19
    Processing order for user 21fd133aThread-13
    Processing order for user 1dd04ff4Thread-6
    User 1dd04ff4Thread-6 is allocated number 6 mobile phone. Number of mobile phones left: 4.
    Processing order for user e5977112Thread-3
    Processing order for user 4d7a8a2bThread-4
    User e5977112Thread-3 is allocated number 7 mobile phone. Number of mobile phones left: 3.
    Processing order for user 18967410Thread-15
    User 18967410Thread-15 is allocated number 9 mobile phone. Number of mobile phones left: 1.
    Processing order for user e4f51568Thread-14
    User 21fd133aThread-13 is allocated number 5 mobile phone. Number of mobile phones left: 5.
    User e8391c0eThread-19 is allocated number 4 mobile phone. Number of mobile phones left: 6.
    Processing order for user d895d3f1Thread-12
    User d895d3f1Thread-12 order failed.
    Processing order for user 7b8d2526Thread-11
    User 7b8d2526Thread-11 order failed.
    Processing order for user d7ca1779Thread-8
    User d7ca1779Thread-8 order failed.
    Processing order for user 74fca0ecThread-1
    User 74fca0ecThread-1 order failed.
    User e04934ddThread-5 is allocated number 1 mobile phone. Number of mobile phones left: 9.
    User e4f51568Thread-14 is allocated number 10 mobile phone. Number of mobile phones left: 0.
    Processing order for user aae76a83Thread-7
    User aae76a83Thread-7 order failed.
    Processing order for user c638d2cfThread-2
    User c638d2cfThread-2 order failed.
    Processing order for user 2de29a4eThread-17
    User 2de29a4eThread-17 order failed.
    Processing order for user 40a46ba0Thread-18
    User 40a46ba0Thread-18 order failed.
    Processing order for user 211fd9c7Thread-9
    User 211fd9c7Thread-9 order failed.
    Processing order for user 911b83fcThread-16
    User 911b83fcThread-16 order failed.
    User 4d7a8a2bThread-4 is allocated number 8 mobile phone. Number of mobile phones left: 2.

  5. Add the lock code back to CaseTest, and compile and run the code. The following shows sequential purchases:

    Processing order for user eee56fb7Thread-16
    User eee56fb7Thread-16 is allocated number 1 mobile phone. Number of mobile phones left: 9.
    Processing order for user d6521816Thread-2
    User d6521816Thread-2 is allocated number 2 mobile phone. Number of mobile phones left: 8.
    Processing order for user d7b3b983Thread-19
    User d7b3b983Thread-19 is allocated number 3 mobile phone. Number of mobile phones left: 7.
    Processing order for user 36a6b97aThread-15
    User 36a6b97aThread-15 is allocated number 4 mobile phone. Number of mobile phones left: 6.
    Processing order for user 9a973456Thread-1
    User 9a973456Thread-1 is allocated number 5 mobile phone. Number of mobile phones left: 5.
    Processing order for user 03f1de9aThread-14
    User 03f1de9aThread-14 is allocated number 6 mobile phone. Number of mobile phones left: 4.
    Processing order for user 2c315ee6Thread-11
    User 2c315ee6Thread-11 is allocated number 7 mobile phone. Number of mobile phones left: 3.
    Processing order for user 2b03b7c0Thread-12
    User 2b03b7c0Thread-12 is allocated number 8 mobile phone. Number of mobile phones left: 2.
    Processing order for user 75f25749Thread-0
    User 75f25749Thread-0 is allocated number 9 mobile phone. Number of mobile phones left: 1.
    Processing order for user 26c71db5Thread-18
    User 26c71db5Thread-18 is allocated number 10 mobile phone. Number of mobile phones left: 0.
    Processing order for user c32654dbThread-17
    User c32654dbThread-17 order failed.
    Processing order for user df94370aThread-7
    User df94370aThread-7 order failed.
    Processing order for user 0af94cddThread-5
    User 0af94cddThread-5 order failed.
    Processing order for user e52428a4Thread-13
    User e52428a4Thread-13 order failed.
    Processing order for user 46f91208Thread-10
    User 46f91208Thread-10 order failed.
    Processing order for user e0ca87bbThread-9
    User e0ca87bbThread-9 order failed.
    Processing order for user f385af9aThread-8
    User f385af9aThread-8 order failed.
    Processing order for user 46c5f498Thread-6
    User 46c5f498Thread-6 order failed.
    Processing order for user 935e0f50Thread-3
    User 935e0f50Thread-3 order failed.
    Processing order for user d3eaae29Thread-4
    User d3eaae29Thread-4 order failed.

Sitemizi ve deneyiminizi iyileştirmek için çerezleri kullanırız. Sitemizde tarama yapmaya devam ederek çerez politikamızı kabul etmiş olursunuz. Daha fazla bilgi edinin

Feedback

Feedback

Feedback

0/500

Selected Content

Submit selected content with the feedback