java中实战项目的缓存应用

版权声明:转载请注明出处 https://blog.csdn.net/chenmingxu438521/article/details/90110614

一、背景

1.在这里不谈什么redis缓存,这里我们主要谈谈java里的缓存工具。

二、项目例子

1.依赖

<dependency>
  <groupId>com.google.guava</groupId>
  <artifactId>guava</artifactId>
  <version>17.0</version>
</dependency>

2.实体类

public class Student {
    private String age;
    private String name;

    public Student(String age, String name) {
        this.age = age;
        this.name = name;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Student{" +
                "age='" + age + '\'' +
                ", name='" + name + '\'' +
                '}';
    }
}

3.缓存类

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import java.util.concurrent.TimeUnit;

public class TestCache {
    //设置了最大的缓存数据10,过期策略10秒(10秒内没写入的话)
    public static final Cache<String,Student> studentCache=
                    CacheBuilder.newBuilder()
                    .maximumSize(10)
                    .expireAfterWrite(10, TimeUnit.SECONDS)
                    .build();
}

4.测试类

public class TestCacheDemo {
    public static void main(String[] args) {
        for (int i=0;i<12;i++){
            studentCache.put(i+"",new Student(i+"","诺言"));
        }
        System.out.println("第一次输出:"+studentCache.getIfPresent("1"));
        for (int i=0;i<12;i++){
            System.out.println(i+"次输出:"+studentCache.getIfPresent(""+i));
        }
        System.out.println("缓存总大小:"+studentCache.size());
        try{
            Thread.sleep(10100L);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("第三次输出:"+studentCache.getIfPresent("10"));
        //获取缓存10,如果null就利用Callable重新计算,所以会输出第四次的结果
        try{
            studentCache.get("10", new Callable<Student>() {
                @Override
                public Student call() throws Exception {
                    return new Student("10","爱你");
                }
            });
        }catch (ExecutionException e){
            e.printStackTrace();
        }
        System.out.println("第四次输出:"+studentCache.getIfPresent("10"));
    }
}

5.结果

第一次输出:null   //缓存的数量限制
0次输出:null
1次输出:null
2次输出:Student{age='2', name='诺言'}
3次输出:Student{age='3', name='诺言'}
4次输出:Student{age='4', name='诺言'}
5次输出:Student{age='5', name='诺言'}
6次输出:Student{age='6', name='诺言'}
7次输出:Student{age='7', name='诺言'}
8次输出:Student{age='8', name='诺言'}
9次输出:Student{age='9', name='诺言'}
10次输出:Student{age='10', name='诺言'}
11次输出:Student{age='11', name='诺言'}
缓存总大小:10
第三次输出:null    //这里因为缓存过期了
第四次输出:Student{age='10', name='爱你'}

三、总结

缓存回收策略

四、结束

Always keep the faith!!!

猜你喜欢

转载自blog.csdn.net/chenmingxu438521/article/details/90110614
今日推荐