1. 程式人生 > >guava快取的使用及與spring的整合

guava快取的使用及與spring的整合

一、guava快取簡介

guava是google為java開發的庫,對jdk進行了擴充套件。在此我們只介紹guava的快取。

guava快取是記憶體快取,也就是資料存在記憶體中的。

二、guava基本使用

1、新增maven依賴

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

2、自定義guava工具類

public class GuavaCacheUtil {
    public static LoadingCache<String, String> strCache = CacheBuilder
            .newBuilder()
            .maximumSize(1000)
            .expireAfterAccess(5, TimeUnit.MINUTES)
            .build(
                    new CacheLoader<String, String>() {
                        @Override
public String load(String s) throws Exception { //當快取中不存在時,自動載入新資料到快取 return null; } } ); /** * 將值存入快取 * * @param key * @param val */ public static void setStr(String key, String val) { strCache.put(key, val); } /** * 從快取中取值 * * @param
key * @return */ public static String getStr(String key) { String val = ""; try { val = strCache.get(key); } catch (ExecutionException e) { } return val; } }

3、使用

public class GuavaCacheMain {
    public static void main(String[] args) {
        String key = "k1";
String val = "v1";
GuavaCacheUtil.setStr(key, val);
String v1 = GuavaCacheUtil.getStr(key);
System.out.println("k1 : " + v1);
String v2 = GuavaCacheUtil.getStr(key);
System.out.println("k2 : " + v2);
}
}
輸出:

k1 : v1
k1 : v1

三、guava快取與spring的整合

1、新增maven依賴

<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>23.0</version>
</dependency>
2、在spring中配置guava快取
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:cache="http://www.springframework.org/schema/cache"
xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/cache
       http://www.springframework.org/schema/cache/spring-cache.xsd
        ">
    <context:component-scan base-package="com.dragon.study" />
    <cache:annotation-driven />
    <bean id="cacheManager" class="org.springframework.cache.guava.GuavaCacheManager">
        <property name="cacheSpecification" value="concurrencyLevel=4,expireAfterAccess=100s,expireAfterWrite=100s" />
        <property name="cacheNames">
            <list>
                <value>guavaCache</value>
            </list>
        </property>
    </bean>
</beans>
3、在服務中使用guava快取
public interface StudentService {
    public Student getStudent(Integer id);
    public Student updateStudent(Student stu);
    public void deleteStudent(Integer id);
    public void deleteAllStudent();
    public void myDelete(Integer id);
}
@Service("studentGuavaCache")
public class StudentGuavaCacheImpl implements StudentService {

    @Cacheable(value = "guavaCache",key="'id_'+#id",condition = "#id<3")
    public Student getStudent(Integer id) {
        Student stu = new Student();
stu.setId(id);
stu.setName("apple");
        return stu;
}

    @CachePut(value = "guavaCache",key="'id_'+#stu.getId()")
    public Student updateStudent(Student stu){
        System.out.println("update stu");
        return stu;
}


    @CacheEvict(value = "guavaCache",key="'id_'+#id")
    public void deleteStudent(Integer id){
        System.out.println("delete student "+id);
}

    public void myDelete(Integer id){
        try {
            StudentService ss = (StudentService) AopContext.currentProxy();
ss.deleteStudent(id);
            return ;
}catch (Exception e){
            e.printStackTrace();
}
        this.deleteStudent(id);
}

    @CacheEvict(value = "guavaCache",allEntries = true)
    public void deleteAllStudent(){
        System.out.println("delete all student ");
}
}
4、測試
public class SpringGuavaCacheMain {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("classpath:spring-guava-cache.xml");
StudentService studentService = (StudentService) ac.getBean("studentGuavaCache");
Integer id =1;
Student stu = studentService.getStudent(id);  //新建快取
stu = studentService.getStudent(id);   //從快取中取
studentService.myDelete(id);
stu = studentService.getStudent(id);   //從快取中取
stu.setName("banana");  //重新設定值
studentService.updateStudent(stu); //更新快取
stu = studentService.getStudent(id); //從快取中取出新值
stu = new Student();  //新例項
stu.setId(0);
studentService.updateStudent(stu);  //用新建的例項進行更新,會新建快取
stu = studentService.getStudent(0);  //從快取中取
studentService.deleteStudent(id);  // 刪除快取
stu = studentService.getStudent(id);  //再次新建快取
id=2;
stu = studentService.getStudent(id); //新建快取
studentService.deleteAllStudent(); //刪除所有快取
id=1;
stu = studentService.getStudent(id); //因所有快取被前一步清除,會新建快取
id=5;
stu = studentService.getStudent(id); //不會新建快取 因為設定了快取條件必須小於3
stu = studentService.getStudent(id); //因沒有快取,不會從快取中取
Assert.notNull(stu);
}
}
輸出:

delete student 1
update stu
update stu
delete student 1
delete all student

四、guava快取與其它形式快取共存

除了guava快取,在還有其它如redis等快取,使用方法類似,在此僅列出其spring的配置檔案

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:cache="http://www.springframework.org/schema/cache"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/cache
       http://www.springframework.org/schema/cache/spring-cache.xsd
        ">
    <context:component-scan base-package="com.dragon.study" />
    <cache:annotation-driven />
    <bean id="cacheManager" class="org.springframework.cache.support.CompositeCacheManager">
        <property name="cacheManagers">
            <list>
                <ref bean="simpleCacheManager" />
                <ref bean="guavaCacheManager" />
            </list>
        </property>
        <property name="fallbackToNoOpCache" value="true" />
    </bean>
    <bean id="simpleCacheManager" class="org.springframework.cache.support.SimpleCacheManager">
        <property name="caches">
            <set>
                <bean class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean" p:name="default" />
                <bean class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean" p:name="mycache" />
                <bean class="com.dragon.tbscheduleStudy.cache.RedisCache" p:name="redisCache" p:timeout="60000" />
            </set>
        </property>
    </bean>
    <bean id="guavaCacheManager" class="org.springframework.cache.guava.GuavaCacheManager">
        <property name="cacheSpecification" value="concurrencyLevel=4,expireAfterAccess=100s,expireAfterWrite=100s" />
        <property name="cacheNames">
            <list>
                <value>guavaCache</value>
            </list>
        </property>
    </bean>
</beans>