当前位置:网站首页>[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
Go to the download address , I downloaded this
Local installation
I unzip it here to D Dish up , That's all the files .
Use vscode Open this file
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 .
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 .
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.
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 .
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 .
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 .
边栏推荐
- @RequestBody注解
- Virtual CD-ROM function how to use and install virtual CD-ROM
- I want 18K. Can I pass it?
- Reliable remote code execution (1)
- qt -- QTabWidget 中支持拖拽TabBar项
- Cause analysis of frequent crash and restart of easynvr-arm cloud terminal
- Opencv optical flow prediction and remap remapping function usage
- 10 zeros of D
- Déplacer Tencent sur le cloud a guéri leur anxiété technologique
- Tools and methods - use code formatting tools in source insight
猜你喜欢

Déplacer Tencent sur le cloud a guéri leur anxiété technologique

PHP短信通知+语音播报自动双呼

Axi low power interface

"One good programmer is worth five ordinary programmers!"

Tools and methods - use code formatting tools in source insight

TP-LINK 1208路由器教程(2)

2D 照片变身 3D 模型,来看英伟达的 AI 新“魔法”!

Use the process monitor tool to monitor process operations on registries and files

Group counting_ Structure and workflow of CPU

【数字IC/FPGA】Booth乘法器
随机推荐
[深度学习][pytorch][原创]crnn在高版本pytorch上训练loss为nan解决办法
PPT绘图相关,快捷键,美观度
Multi gate mixture of experts and code implementation
Déplacer Tencent sur le cloud a guéri leur anxiété technologique
《opencv学习笔记》-- 图像的载入和保存
TP-LINK 1208路由器教程(2)
How to develop hospital information system (his) with SMS notification and voice function
Which is a good CAD drawing software? How to select good software
[the lottery in May has ended, and the list of winners has been announced] special session of techo youth university open course database
"Adobe international certification" Adobe Photoshop adjusts cropping, rotation and canvas size
为什么虚拟机ping的通主机,主机ping不通虚拟机
《opencv学习笔记》-- 感兴趣区域(ROI)、图像混合
I just did it! Visualization of character relationships in Douluo continent
Today's sleep quality record 76 points
计组_cpu的结构和工作流程
[206] use PHP language to generate the code of go language
2D 照片变身 3D 模型,来看英伟达的 AI 新“魔法”!
I pushed my younger brother into Tencent. Look at his benchmark resume!
[latest - lightweight cloud servers - hot sales] new lightweight application server optimization scheme, 1-core 2g5m time limit as low as 99 yuan / year
Google Earth Engine(GEE)—如何新增一个图例在Map面板