Install redis in centos7 and operate redis through node.js

Keywords: Javascript Redis Database firewall node.js

Introduction

Recently, I learned how to connect redis to node.js, so I tried to install cent OS7 in the virtual machine, install redis, and use node.js to operate redis. So take a note by the way.

If there are any mistakes, please correct them.

 

1. Using redis under cent OS7

1.1. Configure the compilation environment:

sudo yum install gcc-c++

 

1.2. Download the source code:

wget http://download.redis.io/releases/redis-4.0.11.tar.gz

 

1.3. Decompress the source code:

tar -zxvf redis-4.0.11.tar.gz

 

1.4. Enter the decompression directory:

cd redis-4.0.11

 

1.5. Enter the decompression directory: execute make to compile Redis:

make MALLOC=libc

After compiling the make command, six executable files are generated in the src directory.

  1. redis-server,
  2. redis-cli,
  3. redis-benchmark,
  4. redis-check-aof,
  5. redis-check-rdb,
  6. redis-sentinel

 

1.6. Install Redis:

make install 

 

1.7. Configure Redis to start with the system:

./utils/install_server.sh

 

1.8. Close the firewall

systemctl stop firewalld.service #Stop firewall
systemctl disable firewalld.service #Prohibit firewall boot-up
firewall-cmd --state #View the default firewall status (not running after closing and running after opening)

 

2. redis configuration

If the redis client and server are in the same machine, they can not be configured. If the redis server is in the virtual machine and the client is in the local system, they need to be configured. Otherwise, the connection may fail.

  • Turn off protection mode.

If you do not close, the connection will fail when you connect through node.js

 config set protected-mode no
  • Set password
// Get password
config get requirepass
    
// Set password 
config set requirepass yourpassword

 

2.1, redis.conf configuration information

redis.conf is the redis configuration file. After modifying the configuration file, redis will need to be restarted to take effect.

 

1. If daemonize needs to run in the background, change this item to yes

2. pidfile configures the address of multiple PIDs by default at / var/run/redis.pid

3. bind binds to ip and only accepts requests from the ip after setting

4. Port listening port, default is 6379

5. loglevel is divided into four levels: debug verbose notice warning

6. logfile is used to configure log file address

7. The number of databases is set by database. The default database is 0.

8. save sets the frequency of redis for database mirroring.

9. Whether rdbcompression compresses image backup or not

10. File name of dbfilename mirror backup file

11. File Placement Path of Dir Database Mirror Backup

12. Slaveof sets up database as slave database of other databases

13. Password Validation for Masterauth Master Database Connection

14. Requriepass needs to use password when setting up login

15. Maxclients Limits the Number of Customers Used Simultaneously

16. Maxmemory sets the maximum memory redis can use

17. Appendonly opens append only mode

18. Appendfsync sets the frequency of appendonly.aof file synchronization (the second way of backing up data)

19. Whether vm-enabled opens virtual memory support (all parameters at the beginning of VM configure virtual memory)

20. vm-swap-file sets the exchange file path of virtual memory

vm-max-memory sets the maximum physical memory size used by redis

22. vm-page-size sets the page size of virtual memory

23. vm-pages sets the total number of pages for exchanging files

24. vm-max-threads sets the number of threads used by VM IO at the same time

25. Glueoutput buf stores small output caches together

26. hash-max-zipmap-entries set the critical value of hash

27. Activerehashing hash

  

3. Operation redis in nodejs

3.1. Installation of redis

// github https://github.com/NodeRedis/node_redis
npm install redis --save

 

3.2. Simple Use

//Introduce redis
var redis = require('redis')
// Connect redis The server
// Connect redis Database, createClient(port,host,options);
// If REDIS On the local machine, the port is the default, write directly createClient()that will do
client = redis.createClient(6379, '192.168.73.128', {
    password: 'lentoo'
});

//Error monitoring?
client.on("error", function (err) {
    console.log(err);
});
client.set('key','value')
client.get('key')

 

3.3. Common API s

  • redis.print

Print api echo via redis

  • set

Store a key-value pair in redis

client.set('key','value')
// Set expiration time 10 s After expiration
client.set('key','value','EX',10)
  • get

Get the value stored in redis

  client.get('key') // value
  • hset

Storage value through hash key

client.hset('hash key','key','value', redis.print)

 

  • hget

Getting values through hash key

client.hget('hash key','key', redis.print)

 

  • hkeys

All "hash key s"

// Traversal hash table"hash key"
client.hkeys("hash key", function (err, replies) {
    console.log(replies.length + " replies:");
    replies.forEach(function (reply, i) {
        console.log("    " + i + ": " + reply);
    });
    client.quit();
});
  • hmset 

Multiple key s, value s can be set at the same time

client.hmset('hash 1', 'key', 'value111', 'key2', 'value222', 'key3', 'value3', redis.print)

 

  • hmget

Multiple key s can be acquired simultaneously

client.hmget('hash 1', 'key', 'key2', 'key3', redis.print)

 

  • publish/subscribe

Publish/Subscribe

const sub = redis.createClient() // Subscriber
const pub = redis.createClient() // Publisher
var msg_count = 0;

sub.on("subscribe", function (channel, count) {
    client.publish("a nice channel", "I am sending a message.");
    client.publish("a nice channel", "I am sending a second message.");
    client.publish("a nice channel", "I am sending my last message.");
});

sub.on("message", function (channel, message) {
    console.log("sub channel " + channel + ": " + message);
    msg_count += 1;
    if (msg_count === 3) {
        sub.unsubscribe();
        sub.quit();
        client.quit();
    }
});

 

  • ready

The redis client connection is triggered when it is ready. Before that, all commands sent to the redis server are queued and sent to the redis server after the read event triggers.

client.on('ready',function(){
    console.log('ready');
})

 

  • connct       

Client triggers after connecting to server

client.on('connect',function(){
    console.log('connect');
})

 

  • reconnecting   

Client triggers when the connection is disconnected and the server is reconnected

client.on('reconnecting ', function (resc) {
    console.log('reconnecting',resc);
})

 

  • error

Error monitoring

client.on("error", function (err) { console.log(err); });

 

  • end

Triggered when the connection is disconnected

client.on('end',function(){
  console.log('end')
})

 

  • createClient

Create a link

redis.createClient([options])
redis.createClient(unix_socket[, options])
redis.createClient(redis_url[, options])
redis.createClient(port[, host][, options])

 

3.4 options Object Properties

attribute Default value describe
host  127.0.0.1 redis server address
port 6379 Port number
connect_timeout 3600000 Connection timeout in ms
password null Password

Posted by Deemo on Sat, 15 Dec 2018 15:12:03 -0800