MapCache.java 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package com.yihu.jw.cache;
  2. import org.springframework.context.annotation.Scope;
  3. import org.springframework.stereotype.Component;
  4. import java.util.HashMap;
  5. import java.util.HashSet;
  6. import java.util.Map;
  7. import java.util.Set;
  8. import java.util.regex.Pattern;
  9. /**
  10. * Created by LiTaohong on 2017/12/04.
  11. */
  12. @Component
  13. @Scope("singleton")
  14. public class MapCache implements Cache {
  15. /**
  16. * 缓存的map,key是module value是对应model的缓存
  17. */
  18. private static Map<String, Map<String, String>> cacha = new HashMap<>();
  19. @Override
  20. public void setData(String module, String key, String value) {
  21. //获取map
  22. Map<String, String> map=cacha.get(module);
  23. if(map==null){
  24. map=new HashMap<>();
  25. cacha.put(module,map);
  26. }
  27. //放入缓存
  28. map.put(key,value);
  29. }
  30. @Override
  31. public String getData(String module, String key) {
  32. Map<String, String> map=cacha.get(module);
  33. if(map==null){
  34. return null;
  35. }
  36. return map.get(key);
  37. }
  38. /**
  39. * 通过正则,获取key值
  40. * @param module
  41. * @param pattern
  42. * @return
  43. */
  44. @Override
  45. public Set<String> keys(String module,String pattern) {
  46. Map<String, String> map=cacha.get(module);
  47. if(map==null){
  48. return null;
  49. }
  50. Set<String> keys = map.keySet();
  51. Set<String> newKeys = new HashSet<String>();
  52. for(String key:keys){
  53. if(Pattern.matches(pattern, key)){
  54. newKeys.add(key);
  55. }
  56. }
  57. return newKeys;
  58. }
  59. @Override
  60. public void removeData(String module, String key) throws Exception {
  61. Map<String, String> map=cacha.get(module);
  62. if(map==null){
  63. throw new Exception("this "+module+" does not exist cache");
  64. }
  65. map.remove(key);
  66. }
  67. }