cache.js 949 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. 'use strict';
  2. const Service = require('egg').Service;
  3. class CacheService extends Service {
  4. async setString(key, value, seconds) {
  5. let {redis} = this.app;
  6. if( !seconds ) return await redis.set(key,value);
  7. return await redis.set(key,value,'EX',seconds);
  8. }
  9. async getString( key ) {
  10. let {redis} = this.app;
  11. return await redis.get(key);
  12. }
  13. async setJSON(key,value,seconds) {
  14. let {redis} = this.app;
  15. value = JSON.stringify(value);
  16. if(!seconds) return await redis.set(key,value);
  17. return await redis.set(key,value,'EX',seconds);
  18. }
  19. async getJSON(key){
  20. let {redis} = this.app;
  21. let data = await redis.get(key);
  22. if( !data ) return;
  23. return JSON.parse(data);
  24. }
  25. async removeCache(key) {
  26. let {redis} = this.app;
  27. let ret = await redis.del( key );
  28. console.log("removeCache-> " + key, ret);
  29. }
  30. }
  31. module.exports = CacheService;