当前位置:网站首页>[Architect (Part 41)] installation of server development and connection to redis database

[Architect (Part 41)] installation of server development and connection to redis database

2022-06-24 11:29:00 A tailed Warbler

Keep creating , Accelerate growth ! This is my participation 「 Nuggets day new plan · 6 Yuegengwen challenge 」 Of the 24 God , Click to see the event details

Local installation Redis

download

Download address

Go to the download address , I downloaded this

image.png

Local installation

I unzip it here to D Dish up , That's all the files .

image.png

Use vscode Open this file

image.png

find requirepass foobared, Copy to a new line , Ahead of # Delete , And clear the space , Otherwise, the password will not be set successfully .

And then foobared Change it to the password you need , Then save , If the identity is not enough, open it as an administrator .

image.png

stay redis The folder is open cmd, perform redis-server.exe  redis.windows.conf, At this time, the interface shows redis Information , Indicates that the service is on normally .

image.png

In order to facilitate the next startup , stay redis Create a new folder under the folder startup.bat file , The content is redis-server.exe  redis.windows.conf.

image.png

Don't close this window , Continue opening one cmd, perform redis-cli.exe -h 127.0.0.1 -p 6379 -a xiaowei123 enter

among xiaowei123 That's the password you set up before .

And then use set key value Set the cache , Use get key Read cache , The following interface shows that the local installation is successful .

image.png

Connect Redis

Install... In the project Redis

Here in order to follow the teacher to learn , Specify the installation version , Different syntax in the new version will lead to errors .

npm i [email protected]3.0.2 -S

To configure Redis

// src\config\envs\dev.js

module.exports = {
  // redis  Connection configuration 
  redisConf: {
    port: '6379',
    host: '127.0.0.1',
    password: 'xiaowei123'
  },
}

Package settings / Access to the cache

// src\cache\index.js

const redisClient = require('../db/redis')

/** * redis set * @param {string} key key * @param {string|Object} val val * @param {number} timeout  Expiration time , Company  s , Default  1h */
function cacheSet(key, val, timeout = 60 * 60) {
  let formatVal
  if (typeof val === 'object') {
    formatVal = JSON.stringify(val)
  } else {
    formatVal = val
  }
  redisClient.set(key, formatVal)
  redisClient.expire(key, timeout)
}

/** * redis get * @param {string} key key */
function cacheGet(key) {
  const promise = new Promise((resolve, reject) => {
    redisClient.get(key, (err, val) => {
      if (err) {
        reject(err)
        return
      }
      if (val == null) {
        resolve(null)
        return
      }

      try {
        resolve(JSON.parse(val))
      } catch (ex) {
        resolve(val)
      }
    })
  })
  return promise
}

module.exports = {
  cacheSet,
  cacheGet,
}

Test connection Redis database

// src\db\redis.js

const redis = require('redis')
const { redisConf } = require('../config/index')

//  Create client 
const { port, host, password } = redisConf
const opt = {}
if (password) {
  opt.password = password // prd  The environment requires a password 
}
const redisClient = redis.createClient(port, host, opt)
redisClient.on('error', err => {
  console.error('redis connect error', err)
})
//  function  node src/db/redis.js  Make a test connection 
redisClient.on('connect', () => {
  console.log('redis connect success')
  redisClient.set('foo', 'bar', redis.print) // => "Reply: OK"
  redisClient.get('foo', redis.print) // => "Reply: bar"
  redisClient.quit()
})

module.exports = redisClient

Console execution node src/db/redis.js, appear success It means the connection is successful .

image.png

Further test the database connection

// src\routes\index.js
const router = require('koa-router')()
const packageInfo = require('../../package.json')
const testMysqlConn = require('../db/mysql2')
const ENV = require('../utils/env')
const { WorkModel } = require('../models/WorksModel')
const { cacheGet, cacheSet } = require('../cache/index')

//  Test database connection 
router.get('/api/db-check', async (ctx) => {
  //  test  mysql  Database connection 
  const mysqlRes = await testMysqlConn()

  //  test  mongodb  Database connection 
  let mongodbConn
  try {
    mongodbConn = true
    await WorkModel.findOne()
  } catch (error) {
    mongodbConn = false
  }

  //  test  Redis  Connect 
  cacheSet('name', 'biz editor sever OK - by redis')
  const redisTestVal = await cacheGet('name')

  ctx.body = {
    errno: 0,
    data: {
      name: 'biz editor server',
      version: packageInfo.version,
      ENV,
      mysqlConn: mysqlRes.length > 0,
      mongodbConn,
      redisConn: redisTestVal != null,
    }
  }
})

module.exports = router

visit http://localhost:3000/api/db-check,redisConn As the result of the true, It also further proves that Redis Database connection succeeded .

image.png

原网站

版权声明
本文为[A tailed Warbler]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/175/202206241013570312.html