SpringBoot项目使用guava构建本地缓存

一、项目新建:

新建Spring Starter Project会自动引入Spring框架所需的依赖,勾选Web、数据库等相关依赖,会将自动生成pom文件并下载所需jar包。

注意:

groupID:一般分两级,例如org.apache, ORG为所在区域类似的有com,apache为公司名

artifactID:项目id,例如tomcat

package name:为启动类所在的包

 

二、引入依赖

pom文件中加入guava依赖

       <dependency>

             <groupId>com.google.guavagroupId>

             <artifactId>guavaartifactId>

             <version>25.1-jreversion>

         dependency>

三、编写本地缓存类

public class GuavaCache {

     //创建静态缓存

     private static volatile CachestringCacheForTest;

     //单例模式获取缓存

     public static CachegetStringCache(){

         if(stringCacheForTest==null) {

              synchronized(GuavaCache.class) {

                   if(stringCacheForTest==null) {

                       //通过CacheBuilderbuild方法创建缓存

                       stringCacheForTest= CacheBuilder.newBuilder()

                                .maximumSize(512)//根据系统内存大小设置缓存存储数量

                                .expireAfterAccess(60, TimeUnit.SECONDS)//设置缓存失效时间

                                .build();

                   }

              }

         }

         return stringCacheForTest;

     }

}

四、使用缓存

@Service(StringCacheService.BEAN_ID)

public class StringCacheServiceImpl implements StringCacheService{

      @Override

      public void setCache(String s) {

           CachestringCache = GuavaCache.getStringCache();//获取缓存

           stringCache.put(s, s);

           System.out.println("将字符串存入本地缓存");

      }

      @Override

      public String getStringFromCache(String s) {

           CachestringCache = GuavaCache.getStringCache();//获取缓存

           String result = stringCache.getIfPresent(s);

           if(StringUtils.isEmpty(result)) {

                 System.out.println("本地缓存不存在该字符串");

           }else {

                 System.out.println("从本地缓存中取出该字符串");

           }

           return result;

      }

}

通过Cache的set方法添加缓存,使用get方法从缓存中取数据

 

你可能感兴趣的:(Spring)