jackieli123723 / jackieli123723.github.io

✅lilidong 个人博客
9 stars 0 forks source link

CentOS 7 安装 Redis 运行node程序 #60

Open jackieli123723 opened 6 years ago

jackieli123723 commented 6 years ago

linux cenos7 安装redis

 [root@VM_134_103_redhat node-redis]# yum install redis -y
 [root@VM_134_103_redhat node-redis]# systemctl start redis
[root@VM_134_103_redhat node-redis]# systemctl enable redis
Created symlink from /etc/systemd/system/multi-user.target.wants/redis.service to /usr/lib/systemd/system/redis.service.
[root@VM_134_103_redhat node-redis]# systemctl status redis
● redis.service - Redis persistent key-value database
   Loaded: loaded (/usr/lib/systemd/system/redis.service; enabled; vendor preset: disabled)
  Drop-In: /etc/systemd/system/redis.service.d
           └─limit.conf
   Active: active (running) since Tue 2018-06-26 11:10:28 CST; 27s ago
 Main PID: 536 (redis-server)
   CGroup: /system.slice/redis.service
           └─536 /usr/bin/redis-server 127.0.0.1:6379
Jun 26 11:10:28 VM_134_103_redhat systemd[1]: Started Redis persistent key-value database.
Jun 26 11:10:28 VM_134_103_redhat systemd[1]: Starting Redis persistent key-value database...
[root@VM_134_103_redhat node-redis]#  ps -ef | grep redis
redis      536     1  0 11:10 ?        00:00:00 /usr/bin/redis-server 127.0.0.1:6379
root       606  7565  0 11:11 pts/1    00:00:00 grep --color=auto redis
[root@VM_134_103_redhat node-redis]# redis-cli ping
PONG
[root@VM_134_103_redhat node-redis]# ss -nlp | grep redis
tcp    LISTEN     0      128    127.0.0.1:6379                  *:*                   users:(("redis-server",pid=536,fd=4))
[root@VM_134_103_redhat node-redis]# redis-cli
127.0.0.1:6379> set name 1
OK
127.0.0.1:6379> get name
"1"
127.0.0.1:6379> 
[root@VM_134_103_redhat node-redis]# ss -nlp | grep redis
tcp    LISTEN     0      128    127.0.0.1:6379                  *:*                   users:(("redis-server",pid=536,fd=4))

[root@VM_134_103_redhat redusers]# netstat -an | grep 6379
tcp        0      0 127.0.0.1:6379          0.0.0.0:*               LISTEN     
tcp        0      0 127.0.0.1:6379          10.139.134.103:43972    ESTABLISHED
tcp        0      0 127.0.0.1:43972         127.0.0.1:6379          ESTABLISHED
[root@VM_134_103_redhat redusers]# redis-server
15836:C 26 Jun 16:33:20.637 # Warning: no config file specified, using the default config. In order to specify a config file use redis-server /path/to/redis.conf
                _._                                                  
           _.-``__ ''-._                                             
      _.-``    `.  `_.  ''-._           Redis 3.0.4 (00000000/0) 64 bit
  .-`` .-```.  ```\/    _.,_ ''-._                                   
 (    '      ,       .-`  | `,    )     Running in standalone mode
 |`-._`-...-` __...-.``-._|'` _.-'|     Port: 6379
 |    `-._   `._    /     _.-'    |     PID: 15836
  `-._    `-._  `-./  _.-'    _.-'                                   
 |`-._`-._    `-.__.-'    _.-'_.-'|                                  
 |    `-._`-._        _.-'_.-'    |           http://redis.io        
  `-._    `-._`-.__.-'_.-'    _.-'                                   
 |`-._`-._    `-.__.-'    _.-'_.-'|                                  
 |    `-._`-._        _.-'_.-'    |                                  
  `-._    `-._`-.__.-'_.-'    _.-'                                   
      `-._    `-.__.-'    _.-'                                       
          `-._        _.-'                                           
              `-.__.-'                                               

15836:M 26 Jun 16:33:20.638 # WARNING: The TCP backlog setting of 511 cannot be enforced because /proc/sys/net/core/somaxconn is set to the lower value of 128.
15836:M 26 Jun 16:33:20.638 # Server started, Redis version 3.0.4
15836:M 26 Jun 16:33:20.638 * The server is now ready to accept connections on port 6379

上面的命令是启动redis 然后配置是用的默认的,如果需要修改配置

[root@VM_134_103_redhat node-redis]# vi /etc/redis.conf
 [root@VM_134_103_redhat node-redis]# systemctl restart redis 重启

跑一个nodejs 配合redis存储的demo

image

//添加记录到redis
[root@VM_134_103_redhat redusers]# node app.js 
Server started on port 4444
Connected to Redis...
OK
OK

//app.js
const express = require('express');
const exphbs = require('express-handlebars');
const path = require('path');
const bodyParser = require('body-parser');
const methodOverride = require('method-override');
const redis = require('redis');

// Create Redis Client
let client = redis.createClient();

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

// Set Port
const port = 4444;

// Init app
const app = express();

// View Engine\
app.engine('handlebars', exphbs({defaultLayout:'main'}));
app.set('view engine', 'handlebars');

// body-parser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:false}));

// methodOverride
app.use(methodOverride('_method'));

// Search Page
app.get('/', function(req, res, next){
  res.render('searchusers');
});

// Search processing
app.post('/user/search', function(req, res, next){
  let id = req.body.id;

  client.hgetall(id, function(err, obj){
    if(!obj){
      res.render('searchusers', {
        error: 'User does not exist'
      });
    } else {
      obj.id = id;
      res.render('details', {
        user: obj
      });
    }
  });
});

// Add User Page
app.get('/user/add', function(req, res, next){
  res.render('adduser');
});

// Process Add User Page
app.post('/user/add', function(req, res, next){
  let id = req.body.id;
  let first_name = req.body.first_name;
  let last_name = req.body.last_name;
  let email = req.body.email;
  let phone = req.body.phone;

  client.hmset(id, [
    'first_name', first_name,
    'last_name', last_name,
    'email', email,
    'phone', phone
  ], function(err, reply){
    if(err){
      console.log(err);
    }
    console.log(reply);
    res.redirect('/');
  });
});

// Delete User
app.delete('/user/delete/:id', function(req, res, next){
  //client.del(req.params.id);
  client.del(req.params.id,function(err,reply){
     if (reply == 1) {
        console.log('删除成功',req.params.id);
    } else {
        console.log('删除失败',req.params.id);
    }
  });
  res.redirect('/');
});

app.listen(port, function(){
  console.log('Server started on port '+port);
});

//验证 redis 是否存在
[root@VM_134_103_redhat redusers]# node index.js 
redis ready: undefined
Entering monitoring mode.
{ first_name: '2', last_name: '2', email: '2', phone: '2' }
Key Exists!!!
//index.js
var redis = require('redis');

// 可配置项
var host = '127.0.0.1';
var port = 6379;

var client = redis.createClient(port, host, {});

client.on('ready', (res) => {
    console.log('redis ready: ' + res);
});

client.on('error', (err) => {
    console.log('connect redis error: ' + err);
    process.exit(2);
});

client.monitor(function (err, res) {
    console.log("Entering monitoring mode.");
});

//查看noderedis 中存在的
client.hgetall("2", function(err, reply) {
    // reply is null when the key is missing
    console.log(reply);
});

client.exists('2', function(err, reply) {
    if (reply == 1) {
        console.log('Key Exists!!!');
    } else {
        console.log('Key Does Not Exist...');
    }
})
jackieli123723 commented 5 years ago

默认安装的node版本

sudo yum install epel-release

yum install -y nodejs npm

npm install -g n

现在node -v 是 6.1.34 版本

然后n stable || n latest

切换node 失败 你需要执行 下面三条命令

export NODE_HOME=/usr/local
export PATH=$NODE_HOME/bin:$PATH
export NODE_PATH=$NODE_HOME/lib/node_modules:$PATH

[root@localhost bin]# node -v
v11.2.0
[root@localhost bin]# cd /home
[root@localhost home]# ll
总用量 4
drwx------. 16 jackeili jackeili 4096 11月 22 14:03 jackeili
drwxr-xr-x.  8 root     root      147 11月 22 14:13 pm2-reboot
[root@localhost home]# n
node/10.0.0
[root@localhost home]# node -v
v10.0.0