ProxyCache.java 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. package com.yiidata.intergration.web.modules.sys.cache;
  2. import org.springframework.cache.Cache;
  3. import org.springframework.cache.support.SimpleValueWrapper;
  4. import java.util.concurrent.Callable;
  5. /**
  6. *
  7. * Icache 缓存的代理,用于支持 Spring CacheManager, @Cacheable
  8. *
  9. * <pre>
  10. *
  11. * User: zhenqin
  12. * Date: 15/3/9
  13. * Time: 09:59
  14. *
  15. * </pre>
  16. *
  17. * @author zhenqin
  18. */
  19. public class ProxyCache implements Cache {
  20. /**
  21. * cache 名称
  22. */
  23. private final String name;
  24. /**
  25. * 实际缓存系统
  26. */
  27. private final ICache cache;
  28. public ProxyCache(String name, ICache cache) {
  29. this.name = name;
  30. this.cache = cache;
  31. }
  32. public ProxyCache(ICache cache) {
  33. this(cache.getClass().getSimpleName(), cache);
  34. }
  35. @Override
  36. public final String getName() {
  37. return name;
  38. }
  39. @Override
  40. public final Object getNativeCache() {
  41. return cache;
  42. }
  43. @Override
  44. public ValueWrapper get(Object key) {
  45. Object value = this.cache.get(key instanceof String ? (String)key : String.valueOf(key));
  46. return toWrapper(value);
  47. }
  48. public <T> T get(Object key, Class<T> type) {
  49. Object value = this.cache.get(key instanceof String ? (String)key : String.valueOf(key));
  50. if (value != null && type != null && !type.isInstance(value)) {
  51. throw new IllegalStateException("Cached value is not of required type [" + type.getName() + "]: " + value);
  52. }
  53. return (T) value;
  54. }
  55. @Override
  56. public <T> T get(Object keyO, Callable<T> valueLoader) {
  57. String key = keyO instanceof String ? (String)keyO : String.valueOf(keyO);
  58. return (T)this.cache.get(key);
  59. }
  60. @Override
  61. public void put(Object key, Object value) {
  62. this.cache.add(key instanceof String ? (String)key : String.valueOf(key), value);
  63. }
  64. public ValueWrapper putIfAbsent(Object keyO, final Object value) {
  65. String key = keyO instanceof String ? (String)keyO : String.valueOf(keyO);
  66. Object v = cache.get(key);
  67. if(v == null) {
  68. this.cache.add(key, value);
  69. return toWrapper(value);
  70. }
  71. return null;
  72. }
  73. @Override
  74. public void evict(Object key) {
  75. this.cache.remove(key instanceof String ? (String)key : String.valueOf(key));
  76. }
  77. @Override
  78. public void clear() {
  79. this.cache.clear();
  80. }
  81. private ValueWrapper toWrapper(Object value) {
  82. return (value != null ? new SimpleValueWrapper(value) : null);
  83. }
  84. }