体验一下nest.js利用缓存带来的方便
2022/2/14 23:22:57
本文主要是介绍体验一下nest.js利用缓存带来的方便,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
目前es6出了两种新类型,分别是map与set:https://www.runoob.com/w3cnote/es6-map-set.html
今天在写一个项目时,就用到map类
export class InterfaceService { constructor(@InjectRepository(InterfaceEntity) public readonly interfaceRepository : Repository<InterfaceEntity>){ } // 加一级缓存 interfaceMap = new Map() async get_interface(interfaceName){ //判断请求是否有根据名字查询 if(!interfaceName){ let data = this.interfaceMap.has("all")?this.interfaceMap.get("all"):this.interfaceRepository.query("select * from interface") //刷新缓存 if(!this.interfaceMap.has("all")){ this.interfaceMap.set("all",this.interfaceRepository.query("select * from interface")) } return data }else{ if(this.interfaceMap.has(interfaceName)){ return this.interfaceMap.get(interfaceName) }else{ let res = await this.interfaceRepository.find({"interface_name":interfaceName}).then(result=>{ return result }) this.interfaceMap.set(interfaceName,res) console.log(res,"service") return res } } }
用了缓存之后,响应时间迅速减小,减少了对数据库的访问
但是有个问题,缓存什么时候更新呢?百度了一下:
1.利用定时器定时刷新
2.利用lru-cache(PS:要好好学习一下)
鉴于我的项目这几个接口并不需要很多的增删改,所以我决定在增删改的时候清空
cache就好
this.interfaceMap.clear()
这篇关于体验一下nest.js利用缓存带来的方便的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-10-04package.json 文件位置在哪?-icode9专业技术文章分享
- 2024-10-01Craco.js学习:从入门到实践指南
- 2024-10-01Create-React-App学习:入门与实践指南
- 2024-10-01CSS-in-JS学习:从入门到实践指南
- 2024-09-30JSX语法学习:从入门到初步掌握
- 2024-09-30Mock.js学习:入门教程与实战演练
- 2024-09-30React Hooks学习:从入门到实践
- 2024-09-30受控组件学习:React中的基础入门教程
- 2024-09-29JS定时器教程:初学者必看指南
- 2024-09-29JS对象教程:初学者的全面指南