首页 > 代码库 > Guava 和 spring 整合使用(这里只用到了缓存)

Guava 和 spring 整合使用(这里只用到了缓存)

  最近做的项目需要使用缓存,最初考虑redis,但是实际不需要功能那么强大,只需要缓存即可,redis还需要安装等,项目也比较赶,就用guava

  

技术分享
  1 import com.google.common.cache.CacheBuilder;
  2 import com.google.common.cache.CacheBuilderSpec;
  3 
  4 import org.springframework.cache.Cache;
  5 import org.springframework.cache.support.SimpleValueWrapper;
  6 
  7 import java.io.Serializable;
  8 import java.util.concurrent.TimeUnit;
  9 
 10 import static com.google.common.base.Preconditions.checkNotNull;
 11 
 12 /**
 13  * *********************************************************
 14  * <p/>
 15  * Author:     XiJun.Gong
 16  * Date:       2016-08-22 15:47
 17  * Version:    default 1.0.0
 18  * Class description:
 19  * <p/>
 20  * *********************************************************
 21  * 
 22  * update by mll: 由配置文件提供缓存大小(cacheSize)和时长(timeLength) 
 23  * 构造方法传入---------------------
 24  */
 25 public class GuavaCache implements Cache {
 26 
 27 
 28     private static final Object NULL_HOLDER = new NullHolder();
 29 
 30     private final String name;
 31 
 32     private final com.google.common.cache.Cache<Object, Object> store;
 33 
 34     private final boolean allowNullValues;
 35     
 36     /**
 37      * Create a new GuavaCache with the specified name.
 38      *
 39      * @param name the name of the cache
 40      */
 41     public GuavaCache(String name,Long cacheSize,Long timeLength) {
 42         this(name, CacheBuilder.newBuilder(), true,cacheSize,timeLength);
 43     }
 44 
 45     /**
 46      * Create a new GuavaCache with the specified name.
 47      *
 48      * @param name            the name of the cache
 49      * @param allowNullValues whether to accept and convert null values for this cache
 50      */
 51     public GuavaCache(String name, boolean allowNullValues,Long cacheSize,Long timeLength) {
 52         this(name, CacheBuilder.newBuilder(), allowNullValues,cacheSize,timeLength);
 53     }
 54 
 55     /**
 56      * Create a new GuavaCache using the specified name and {@link com.google.common.cache.CacheBuilderSpec specification}
 57      *
 58      * @param name the name of the cache
 59      * @param spec the cache builder specification to use to build he cache
 60      */
 61     public GuavaCache(String name, CacheBuilderSpec spec, boolean allowNullValues,Long cacheSize,Long timeLength) {
 62         this(name, CacheBuilder.from(spec), allowNullValues,cacheSize,timeLength);
 63     }
 64 
 65     /**
 66      * Create a new GuavaCache using the specified name and {@link CacheBuilderSpec specification}
 67      *
 68      * @param name    the name of the cache
 69      * @param builder the cache builder to use to build the cache
 70      */
 71     public GuavaCache(String name, CacheBuilder<Object, Object> builder, boolean allowNullValues,Long cacheSize,Long timeLength) {
 72         this.name = checkNotNull(name, "name is required");
 73         this.allowNullValues = allowNullValues;
 74         this.store = builder.maximumSize(cacheSize).
 75                 expireAfterWrite(timeLength, TimeUnit.MINUTES).
 76                 build();
 77     }
 78 
 79     @Override
 80     public String getName() {
 81         return this.name;
 82     }
 83 
 84     @Override
 85     public com.google.common.cache.Cache<Object, Object> getNativeCache() {
 86         return this.store;
 87     }
 88 
 89     @Override
 90     public ValueWrapper get(Object key) {
 91         Object value = http://www.mamicode.com/this.store.getIfPresent(key);
 92         return (value != null ? new SimpleValueWrapper(fromStoreValue(value)) : null);
 93     }
 94 
 95     @Override
 96     public void put(Object key, Object value) {
 97         this.store.put(key, value);
 98     }
 99 
100     /**
101      * remove the key of object
102      *
103      * @param key
104      */
105     @Override
106     public void evict(Object key) {
107         this.store.invalidate(key);
108     }
109 
110     /**
111      * clear all
112      */
113     @Override
114     public void clear() {
115         this.store.invalidateAll();
116     }
117 
118     /**
119      * Convert the given value from the internal store to a user value
120      * returned from the get method (adapting {@code null}).
121      *
122      * @param storeValue the store value
123      * @return the value to return to the user
124      */
125     protected Object fromStoreValue(Object storeValue) {
126         if (this.allowNullValues && storeValue =http://www.mamicode.com/= NULL_HOLDER) {
127             return null;
128         }
129         return storeValue;
130     }
131 
132     /**
133      * Convert the given user value, as passed into the put method,
134      * to a value in the internal store (adapting {@code null}).
135      *
136      * @param userValue the given user value
137      * @return the value to store
138      */
139     protected Object toStoreValue(Object userValue) {
140         if (this.allowNullValues && userValue =http://www.mamicode.com/= null) {
141             return NULL_HOLDER;
142         }
143         return userValue;
144     }
145 
146 
147     @SuppressWarnings("serial")
148     private static class NullHolder implements Serializable {
149 
150     }
151 
152 
153     @Override
154     public <T> T get(Object key, Class<T> type) {
155         // TODO Auto-generated method stub
156         return null;
157     }
158 
159     @Override
160     public ValueWrapper putIfAbsent(Object key, Object value) {
161         // TODO Auto-generated method stub
162         return null;
163     }
164 }
GuavaCache
技术分享
  1 import java.util.Collection;
  2 import java.util.Collections;
  3 
  4 import org.springframework.cache.Cache;
  5 import org.springframework.cache.transaction.AbstractTransactionSupportingCacheManager;
  6 import org.springframework.util.StringUtils;
  7 
  8 import cn.goldencis.tsa.common.utils.GuavaCache;
  9 
 10 import com.google.common.cache.CacheBuilder;
 11 
 12 /**
 13  * *********************************************************
 14  * <p/>
 15  * Author:     XiJun.Gong
 16  * Date:       2016-08-22 16:09
 17  * Version:    default 1.0.0
 18  * Class description:
 19  * <p> {@link org.springframework.cache.CacheManager} implementation backed by {@link GuavaCache}.</p>
 20  * <p/>
 21  * *********************************************************
 22  * 
 23  * update by mll: 由配置文件提供缓存大小(cacheSize)和时长(timeLength) 
 24  * 由spring 注入,配置文件提供
 25  */
 26 public class GuavaCacheManager extends AbstractTransactionSupportingCacheManager {
 27     private Collection<GuavaCache> caches;
 28 
 29     private String spec;
 30 
 31     private volatile CacheBuilder<Object, Object> cacheBuilder;
 32     
 33     private Long cacheSize;
 34   
 35     private Long timeLength;
 36 
 37     private boolean allowNullValues = true;
 38 
 39     public GuavaCacheManager() {
 40     }
 41 
 42     public void setCaches(Collection<GuavaCache> caches) {
 43         this.caches = caches;
 44     }
 45 
 46     public void setSpec(String spec) {
 47         this.spec = spec;
 48     }
 49 
 50     public String getSpec() {
 51         return spec;
 52     }
 53 
 54     public void setAllowNullValues(boolean allowNullValues) {
 55         this.allowNullValues = allowNullValues;
 56     }
 57 
 58     public boolean isAllowNullValues() {
 59         return allowNullValues;
 60     }
 61 
 62     @Override
 63     protected Collection<? extends Cache> loadCaches() {
 64         return (caches != null) ? caches : Collections.<GuavaCache>emptyList();
 65     }
 66 
 67     @Override
 68     public Cache getCache(String name) {
 69         Cache cache = super.getCache(name);
 70         if (cache == null) {
 71             // create a new cache
 72             cache = createGuavaCache(name);
 73 
 74             // add to collection of available caches
 75             addCache(cache);
 76         }
 77         return cache;
 78     }
 79 
 80     private GuavaCache createGuavaCache(String name) {
 81         // create GuavaCache
 82         return new GuavaCache(name, getCacheBuilder(), allowNullValues,this.cacheSize,this.timeLength);
 83     }
 84 
 85     private CacheBuilder<Object, Object> getCacheBuilder() {
 86         if (cacheBuilder == null) {
 87             synchronized (this) {
 88                 if (cacheBuilder == null) {
 89                     if (StringUtils.hasText(spec)) {
 90                         cacheBuilder = CacheBuilder.from(spec);
 91                     } else {
 92                         cacheBuilder =CacheBuilder.newBuilder();
 93                     }
 94 
 95                 }
 96                 notify();
 97             }
 98         }
 99 
100         return cacheBuilder;
101     }
102     
103     
104     
105     public Long getCacheSize() {
106         return cacheSize;
107     }
108 
109     public void setCacheSize(Long cacheSize) {
110         this.cacheSize = cacheSize;
111     }
112 
113     public Long getTimeLength() {
114         return timeLength;
115     }
116 
117     public void setTimeLength(Long timeLength) {
118         this.timeLength = timeLength;
119     }
120 
121 
122 }
GuavaCacheManager
技术分享
 1 package cn.goldencis.tsa.common.factory;
 2 
 3 import cn.goldencis.tsa.common.utils.GuavaCache;
 4 
 5 import com.google.common.cache.CacheBuilder;
 6 
 7 import org.springframework.beans.factory.BeanNameAware;
 8 import org.springframework.beans.factory.FactoryBean;
 9 import org.springframework.beans.factory.InitializingBean;
10 import org.springframework.util.StringUtils;
11 
12 /**
13  * *********************************************************
14  * <p/>
15  * Author:     XiJun.Gong
16  * Date:       2016-08-22 16:00
17  * Version:    default 1.0.0
18  * Class description:
19  * <p>{@link FactoryBean} for easy configuration of a {@link GuavaCache}.</p>
20  * <p/>
21  * *********************************************************
22  * update by mll: 由配置文件提供缓存大小(cacheSize)和时长(timeLength) 
23  * 由spring 注入,配置文件提供
24  */
25 public class GuavaCacheFactoryBean
26         implements FactoryBean<GuavaCache>, BeanNameAware, InitializingBean {
27 
28     private String name = "";
29 
30     private boolean allowNullValues = true;
31 
32     private String spec;
33 
34     private GuavaCache cache;
35     
36     private Long cacheSize;
37     
38     private Long timeLength;
39 
40     public void setName(String name) {
41         this.name = name;
42     }
43 
44     public void setAllowNullValues(boolean allowNullValues) {
45         this.allowNullValues = allowNullValues;
46     }
47 
48     public void setSpec(String spec) {
49         this.spec = spec;
50     }
51 
52     @Override
53     public void setBeanName(String name) {
54         if (!StringUtils.hasLength(this.name)) {
55             this.name = name;
56         }
57     }
58 
59     @Override
60     public void afterPropertiesSet() throws Exception {
61         if (StringUtils.hasText(this.spec)) {
62             this.cache = new GuavaCache(this.name, CacheBuilder.from(spec), allowNullValues,this.cacheSize,this.timeLength);
63         } else {
64             this.cache = new GuavaCache(this.name, allowNullValues,this.cacheSize,this.timeLength);
65         }
66     }
67 
68     @Override
69     public GuavaCache getObject() throws Exception {
70         return this.cache;
71     }
72 
73     @Override
74     public Class<?> getObjectType() {
75         return GuavaCache.class;
76     }
77 
78     @Override
79     public boolean isSingleton() {
80         return true;
81     }
82 
83     public Long getCacheSize() {
84         return cacheSize;
85     }
86 
87     public void setCacheSize(Long cacheSize) {
88         this.cacheSize = cacheSize;
89     }
90 
91     public Long getTimeLength() {
92         return timeLength;
93     }
94 
95     public void setTimeLength(Long timeLength) {
96         this.timeLength = timeLength;
97     }
98 
99 }
GuavaCacheFactoryBean
技术分享
 1 <!-- cache 配置  start -->
 2     <bean id="cacheManager" class="cn.goldencis.tsa.common.manager.cache.GuavaCacheManager">
 3         <property name="caches">
 4             <list>
 5                 <bean class="cn.goldencis.tsa.common.factory.GuavaCacheFactoryBean" name="msg-cache">
 6                     <property name="cacheSize" value="${guava.cacheSize}"></property>
 7                     <property name="timeLength" value="${guava.timeLength}"></property>
 8                 </bean>
 9             </list>
10         </property>
11         
12         <property name="cacheSize" value="${guava.cacheSize}"></property>
13         <property name="timeLength" value="${guava.timeLength}"></property>
14     </bean>
15     <cache:annotation-driven/>
16     <!-- cache 配置 end -->
spring-context

  不打算深挖了,能用就行吧.

  代码参考 XiJun.Gong 这个仁兄的,如果你看到请给我你的博客链接地址,我再给你粘上地址,我实在找不到你的博客地址了,不好意思!

 

  

Guava 和 spring 整合使用(这里只用到了缓存)