关于Redis的安装搭建见下面链接:
https://blog.csdn.net/kong1287988804/article/details/75645617
这里设置了redis的密码root,下面连接的时候会用到
注意在node中package.json中redis的版本要在3.+不能超过4,否则会连不上;
如果不设置密码那么createClient第三个参数传空对象即可
const express = require("express");
const fetch = require("node-fetch");
const redis = require("redis");
const PORT = process.env.PORT || 5000;
const REDIS_PORT = process.env.REDiS_PORT || 6379;
const REDIS_HOST = '127.0.0.1';
const REDIS_OPTS = {auth_pass: 'root'};
const app = express();
const client = redis.createClient(REDIS_PORT, REDIS_HOST, REDIS_OPTS);
let whiteList = ['http://192.168.80.128:3000']
app.use(function(req,res,next){
let origin = req.headers.origin;
if(whiteList.includes(origin)){
res.setHeader('Access-Control-Allow-Origin', origin);
res.setHeader('Access-Control-Allow-Headers', 'Origin,Accept,Content-Type,X-Requested-With,Authorization,Referer,Access-Control-Allow-Origin,User-Agent');
res.setHeader('Access-Control-Allow-Methods', 'GET,POST,OPTION,DELETE,PUT');
res.setHeader('Access-Control-Expose-Headers', '*');
}
next();
});
client.on('ready', function(){
console.log('ready');
})
client.on('error', function(err){
console.log('error', err);
})
client.on('connect', function(){
client.set('author', 'kong', redis.print);
client.get('author', redis.print);
console.log('connect');
})
// Cache middleware
function cache(req, res, next) {
const { username } = req.params;
client.get(username, (err, data) => {
if (err) throw err;
if (data !== null) {
console.log('走缓存');
// 缓存中有数据,返回缓存中的数据
res.send(setResponse(username, data));
} else {
// 否则继续之前的请求
next();
}
});
}
// 设置响应
function setResponse(username, repos) {
return `<h2>${username} has ${repos} Github repositories</h2>`;
}
// 获取github仓库数量
async function getRepos(req, res, next) {
try {
console.log("Fetching Data...");
const { username } = req.params;
const response = await fetch(`https://api.github.com/users/${username}`);
const data = await response.json();
const repos = data.public_repos;
// 存到redis
// 三个参数分别是键、有效期、值
client.setex(username, 3600, repos);
res.send(setResponse(username, repos));
} catch (error) {
console.error(error);
res.status = 500;
}
}
// 使用中间件,加上第二个参数cache
app.get("/repos/:username", cache, getRepos);
app.listen(5000, () => {
console.log(`App listening on port ${PORT}`);
});
还是用之前zookeeper的index.html测试,加个按钮
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
</head>
<body>
<div id="console1"></div>
<div id="console2"></div>
<div id="container">
<h1>
hello world
</h1>
</div>
<button id="btn1" >点我一下调用zookeeper</button>
<button id="btn2" >点我一下调用redis</button>
</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(function () {
$("#btn1").click(function () {
//alert("hello world");
$.ajax({
method: 'GET',
url: 'http://192.168.80.128:8084/hello',
headers: {
'Service-Name': 'HelloService/Google',
'key': 'url'
},
success: function (data) {
$("#console1").text(data);
//window.open(data)
}
})
});
$("#btn2").click(function () {
$.ajax({
method: 'GET',
url: 'http://192.168.80.128:5000/repos/k1287988804',
success: function (data) {
$("#console2").html(data);
}
})
});
})
</script>
</html>