Nodejs中最好的API缓存lib

作者:佚名

时间:2025-02-03

来源:dev.to

浏览:342

>我看到了一个可以存储有效载荷在内存缓存中并获得更快响应的库之一。>库名是api-cache。缓存路由importexpressfrom'express'importapicachefrom'apicache'letapp=express()letcache=apicache.middlewareapp.get('/api/collection/:id?',cache('5minutes'),(req,res)=>{//dos

在IT行业这个发展更新速度很快的行业,只有不停止的学习,才不会被行业所淘汰。如果你是文章学习者,那么本文《Nodejs中最好的API缓存lib》就很适合你!本篇内容主要包括##content_title##,希望对大家的知识积累有所帮助,助力实战开发!

>我看到了一个可以存储有效载荷在内存缓存中并获得更快响应的库之一。

>

库名是api-cache

。

缓存路由

import express from 'express'
import apicache from 'apicache'

let app = express()
let cache = apicache.middleware

app.get('/api/collection/:id?', cache('5 minutes'), (req, res) => {
  // do some work... this will only occur once per 5 minutes
  res.json({ foo: 'bar' })
})

缓存所有路由

let cache = apicache.middleware

app.use(cache('5 minutes'))

app.get('/will-be-cached', (req, res) => {
  res.json({ success: true })
})

与redis一起使用

import express from 'express'
import apicache from 'apicache'
import redis from 'redis'

let app = express()

// if redisclient option is defined, apicache will use redis client
// instead of built-in memory store
let cachewithredis = apicache.options({ redisclient: redis.createclient() }).middleware

app.get('/will-be-cached', cachewithredis('5 minutes'), (req, res) => {
  res.json({ success: true })
})

缓存组和手动控件

import apicache from 'apicache'
let cache = apicache.middleware

app.use(cache('5 minutes'))

// routes are automatically added to index, but may be further added
// to groups for quick deleting of collections
app.get('/api/:collection/:item?', (req, res) => {
  req.apicacheGroup = req.params.collection
  res.json({ success: true })
})

// add route to display cache performance (courtesy of @killdash9)
app.get('/api/cache/performance', (req, res) => {
  res.json(apicache.getPerformance())
})

// add route to display cache index
app.get('/api/cache/index', (req, res) => {
  res.json(apicache.getIndex())
})

// add route to manually clear target/group
app.get('/api/cache/clear/:target?', (req, res) => {
  res.json(apicache.clear(req.params.target))
})

/*

GET /api/foo/bar --> caches entry at /api/foo/bar and adds a group called 'foo' to index
GET /api/cache/index --> displays index
GET /api/cache/clear/foo --> clears all cached entries for 'foo' group/collection

>我建议您可以使用此api中间件。在该数据库中很少更新。像国家,城市和验证者api数据一样。

*/
image description

共济思议

cozeniths提供web服务,应用程序开发和seo优化

favicon cozeniths.com

今天带大家了解了的相关知识,希望对你有所帮助;关于文章的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

本文内容来源于互联网,如有侵权请联系删除。

相关文章

更多

热门专题

更多
返回顶部