edit-icon download-icon

Introduction to ApsaraDB for Memcache SDK for NodeJS

Last Updated: Dec 21, 2017

Alibaba Cloud SDK for NodeJS is a unified entry for NodeJS developers to use various Alibaba Cloud services. This SDK is developed and maintained by the Alibaba Cloud UED team. Currently, this SDK integrates three Alibaba Cloud services: ApsaraDB for Memcache, OSS, and RDS (MySQL). Code address: https://github.com/aliyun-UED/aliyun-sdk-js.

By using ApsaraDB for Memcache SDK for NodeJS, you can easily access ApsaraDB for Memcache. After obtaining Alibaba Cloud instances through a trial or purchase, you can obtain the corresponding ocsKey and ocsSecret. In this case, use the following code:

  1. //Obtain Alibaba Cloud SDK instances
  2. var ALY = require(‘aliyun-sdk‘);
  3. //Create an ApsaraDB for Memcache instance for OCS
  4. //Where, host is the IP address of the instance
  5. var memcached = ALY.MEMCACHED.createClient(11211, host, {
  6. username: ocsKey,
  7. password: ocsSecret
  8. });
  9. //Write data to OCS.
  10. memcached.add(‘hello‘, world‘, function(err, data) {
  11. //Perform this operation upon data writing failure.
  12. if(err) {
  13. console.log(‘add error:’, err);
  14. return;
  15. }
  16. //Print the returned value upon data writing success.
  17. console.log(‘add success:’, data);
  18. });

With the preceding code, you can easily access and use ApsaraDB for Memcache services. Post-writing reading is also easy, as shown in the following example:

  1. //Query OCS for data.
  2. memcached.get(‘hello‘, function(err, data) {
  3. //Perform this operation upon query error or failure.
  4. if(err) {
  5. console.log(‘get error:’, err);
  6. memcached.end();
  7. return;
  8. }
  9. //Print the returned value upon query success.
  10. console.log(‘get success:’, data.val.toString());
  11. });

This process is as simple as accessing objects in local runtime memory, reflecting the convenience of developing NodeJS and the ease-of-use of Memcache. In addition, this document also describes NodeJS and how to construct an efficient, reliable, and scalable Web application background by using NodeJS along with the ApsaraDB for Memcache SDK.

Introduction to NodeJS

Node.js is a platform for quickly constructing network services and applications. This platform is built on Chrome’s JavaScript runtime; namely, it is actually an encapsulation of the Google V8 engine (applied in Google Chrome browsers).

For NodeJS itself, it runs V8 JavaScript. The V8 JavaScript engine is an underlying JavaScript engine used by Google for its Chrome browsers. However, few users consider what JavaScript would actually do on their clients. In fact, the JavaScript engine is responsible for interpreting and executing code. Google created an ultra-speed interpreter programmed in C++ by using V8. This interpreter provides a unique feature, which allows you to download this engine and build it into any application. The V8 JavaScript engine is not limited to run in a single browser. Therefore, NodeJS uses the V8 JavaScript engine from Google and reconstructs it so that it can be used on servers.

NodeJS features

High performance

The V8 engine uses multiple cutting-edge compilation techniques. This dramatically accelerates the running speed of code programmed in scripting languages such as Javascript and reduces development costs. NodeJS is performance-demanding. Javascript is an event-driven language, and NodeJS uses this feature to program highly-scalable servers. NodeJS uses the architecture named event loop, which makes programming highly-scalable servers easy and secure. You can improve server performance in a variety of ways. However, NodeJS chooses the architecture that can improve performance while reducing development complexities. For user experience, this is a critical feature. Developing and programming are normally complicated and risky. NodeJS bypasses these disadvantages and can still provide better performance.


NodeJS uses a series of non-blocking libraries to support the event loop architecture. Essentially, it provides interfaces for resources including file systems and databases. When NodeJS sends a request to a file system, NodeJS is notified by the corresponding non-blocking interface when the hard disk is ready without having to wait for the hard disk to complete addressing and file retrieval. This model simplifies the access to slow resources in a scalable way and features a high intuition and understandability. For users who are familiar with DOM events such as onmouseover and onclick, this advantage is even more impressive.

Javascript running

Running Javascript on servers is not exclusive to NodeJS but still a powerful function. Inevitably, browser environments limit programming language selection. Also, sharing code between any servers and increasingly-complicated browser client applications can only be implemented through Javascript. While some other platforms also support running Javascript on server side, NodeJS is becoming the most-ideal platform considering the aforementioned features and its recent popularity.

ApsaraDB for Memcache SDK for NodeJSThe ApsaraDB for Memcache service uses the SASL-certification-based Memcached binary transfer protocol. Only few NodeJS open-source modules have implemented this protocol. Specifically, some modules such as memjs can implement SASL certification and the Memcached binary transfer protocol; however, these modules do not support command queuing so that they cannot run new commands until the previous command returns data, which is unacceptable in actual development scenarios. Therefore, ApsaraDB for Memcache SDK for NodeJS adds command queuing, exception handling and automatic reconnection functions based on memjs, allowing NodeJS developers to access ApsaraDB for Memcache quickly.

Code for this open-source project is hosted here.

Developing Web applications with the ApsaraDB for Memcache SDK

The basic usage of the ApsaraDB for Memcache SDK is described at the beginning of this document. For example, if you want to record the total number of accesses to Web applications, you can represent it with a key in ApsaraDB for Memcache, read the value of the key from ApsaraDB for Memcache whenever a user access occurs and then increment the value with 1 and save the updated value to the key. In this scenario, it is ideal to use ApsaraDB for Memcache as multiple ECS instances may act as Web servers and they can read from/write to the same ApsaraDB for Memcache program. Also, this eliminates the issue that the “total number of accesses” data disappears when an ECS instance becomes faulty. Last but not least, the high performance of ApsaraDB for Memcache also guarantees that business needs can be fully met.

Besides that, it is also ideal to use ApsaraDB for Memcache for session storage. Sessions on Web servers can be stored on caching systems including memory, disk file systems, databases and Memcached.

From the performance and availability perspective, it is the best to store sessions on Memcached. Then, how can we do it with NodeJS?

Generally, developing NodeJS Web applications requires an appropriate Web framework. The following uses the most-popular Express Web framework as an example.

The Express framework internally provides support for session processing. It uses memory storage as the default session storage mechanism and use other session storage mechanisms as scalability options. See the following code:

  1. //Create an express instance.
  2. var app = require(“express“);
  3. //Memory storage session
  4. var session = require(‘express-session‘)
  5. //Use the memory storage mechanism for express to process sessions.
  6. app.use(session({ secret: keyboard cat‘, cookie: { maxAge: 60000 }}))
  7. //Process the HTTP request where req indicates the requested object and res indicates the returned object.
  8. app.use(function(req, res) {
  9. //sess indicates the user session for the request, and the cookie carried by the request has been analyzed by express.
  10. //Also, the session corresponding to the cookie has been located and provided from storage.
  11. var sess = req.session
  12. //The following processes the session object.
  13. if (sess.views) {
  14. sess.views++
  15. res.setHeader(‘Content-Type‘, text/html‘)
  16. res.write(‘
  17. views: + sess.views +
  18. ‘)
  19. res.write(‘
  20. expires in: + (sess.cookie.maxAge / 1000) + s
  21. ‘)
  22. res.end()
  23. } else {
  24. //The updated session will be automatically written back to the session storage after the request is fully processed.
  25. sess.views = 1
  26. res.end(‘welcome to the session demo. refresh!’)
  27. }
  28. })

From the preceding code, you can work perfectly with express by implementing the session storage mechanism.

Thank you! We've received your feedback.