spring中添加google的guava缓存(demo)

1.pom文件中配置

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>4.2.4.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>4.2.4.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>19.0</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.20</version>
        </dependency>
    </dependencies>

2.GuavaCacheManagerConfig配置类

package com.zy;

import com.google.common.cache.CacheBuilder;
import com.google.common.collect.Maps;
import org.springframework.cache.Cache;
import org.springframework.cache.guava.GuavaCache;
import org.springframework.cache.transaction.AbstractTransactionSupportingCacheManager;

import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ConcurrentMap;

public class GuavaCacheManagerConfig extends AbstractTransactionSupportingCacheManager {

    private final ConcurrentMap<String, Cache> cacheMap = Maps.newConcurrentMap();
    private Map<String, CacheBuilder> builderMap = Maps.newHashMap();

    @Override
    protected Collection<? extends Cache> loadCaches() {
        return cacheMap.values();
    }

    //获取缓存单例
    @Override
    public Cache getCache(String name) {
        Cache cache = this.cacheMap.get(name);
        if (null == cache) {
            synchronized (this.cacheMap) {
                cache = this.cacheMap.get(name);
                if (null == cache && this.builderMap.containsKey(name)) {
                    CacheBuilder builder = this.builderMap.get(name);
                    cache = createGuavaCache(name, builder);
                    this.cacheMap.put(name, cache);
                }
            }
        }
        return cache;
    }

    private Cache createGuavaCache(String name, CacheBuilder builder) {
        com.google.common.cache.Cache<Object, Object> cache;
        if(builder == null){
            cache = CacheBuilder.newBuilder().build();
        }else{
            cache = builder.build();
        }
        return new GuavaCache(name, cache, isAllowNullValues());
    }

    private boolean isAllowNullValues() {
        return true;
    }

    //配置中多组缓存池注入
    public void setConfigMap(Map<String, CacheBuilder> configMap) {
        this.builderMap = configMap;
    }
}

3.applicationContext-cache-guava.xml配置文件

<?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: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/cache
                           http://www.springframework.org/schema/cache/spring-cache.xsd">

    <!-- 1.将需要加入缓存的类注册进来 -->
    <bean id="guavaService" class="com.zy.GuavaServiceImpl"/>

    <!-- ==========================2.开启guava缓存开始==================== -->
    <!-- 声明缓存注解的开启 -->
    <cache:annotation-driven cache-manager="cacheManager" proxy-target-class="true"/>
    <!-- 声明使用spring管理缓存组 -->
    <bean id="cacheManager" class="org.springframework.cache.support.CompositeCacheManager">
        <property name="cacheManagers">
            <list>
                <ref bean="guavaCacheManager"/>
            </list>
        </property>
        <property name="fallbackToNoOpCache" value="true"/>
    </bean>
    <!-- 缓存的创建的具体实现类注入 class为自定义的类 -->
    <bean id="guavaCacheManager" class="com.zy.GuavaCacheManagerConfig">
        <!-- 此处可以配置一组缓存池对应不同的业务类型 这里实现了一个"guava"的默认缓存并构建 -->
        <property name="configMap">
            <map key-type="java.lang.String" value-type="com.google.common.cache.CacheBuilder">
                <!-- 该缓存与service层实现类上注解上的value相等 -->
                <entry key="guava" value-ref="defaultCacheBuilder"/>
            </map>
        </property>
    </bean>

    <!-- 此处直接构建"guava"默认缓存 -->
    <bean id="defaultCacheBuilder"
          class="com.google.common.cache.CacheBuilder"
          factory-method="from">
        <!-- 缓存池大小 时间(定时回收 缓存项在给定时间内没有被‘写‘访问 回收 还有refreshAfterWrite expireAfterAccess可供使用) 当然还有一些其他可选组件(weakKeys,removalListener and so on!) -->
        <constructor-arg value="maximumSize=10000, expireAfterAccess=5s"/>
    </bean>
    <!-- ==========================2.开启guava缓存结束==================== -->

</beans>

4.GuavaDTO

package com.zy;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class GuavaDTO {

    private Integer id;

    private String name;

}

5.GuavaServiceImpl的实现类

package com.zy;

import org.springframework.cache.annotation.Cacheable;
public class GuavaServiceImpl {
    // spring EL
    // GuavaDTO 普通的DTO
    // @Cacheable(value = "guava", key = "‘testGuavaCache:‘ + #guavaDTO.id + #guavaDTO.name")
    // value 为配置文件中的缓存池名称 key 为键名
    @Cacheable(value = "guava", key = "‘testGuavaCache:‘ + #guavaDTO.id + #guavaDTO.name")
    public void testGuavaCache(GuavaDTO guavaDTO) {
        System.out.println("=======缓存中没有,进入方法来查询了=========");
    }

}

如果service的实现类是删除方法,则在方法上,加上@CacheEvict注解

如果service的实现类是更新方法,则在方法上,加上@CachePut注解(每次执行,都会进入方法)

6.测试类GuavaTest

package com.zy;

import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class GuavaTest {

    @Test
    public void fn() throws InterruptedException {
        ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext-cache-guava.xml");
        GuavaServiceImpl guavaService = (GuavaServiceImpl) applicationContext.getBean("guavaService");
        System.out.println("第1次访问:1号tom==========================");
        guavaService.testGuavaCache(new GuavaDTO(1, "tom"));
        System.out.println("第2次访问:1号tom==========================");
        guavaService.testGuavaCache(new GuavaDTO(1, "tom"));
        guavaService.testGuavaCache(new GuavaDTO(1, "tom"));
        System.out.println("第1次访问:2号jerry==========================");
        guavaService.testGuavaCache(new GuavaDTO(2, "jerry"));
        Thread.sleep(5000);
        /**
         * 此时配置文件中的失效时间是5000ms
         * */
        System.out.println("第3次访问:1号tom==========================");
        guavaService.testGuavaCache(new GuavaDTO(1, "tom"));

    }
}

7.测试结果如下:

原文地址:https://www.cnblogs.com/psy-code/p/9571602.html

时间: 2024-08-10 10:45:57

spring中添加google的guava缓存(demo)的相关文章

百家搜索:在网站中添加Google、百度等搜索引擎

来源:http://www.ido321.com/1143.html 看到一些网站上添加了各种搜索引擎.如Google.百度.360.有道等,就有点好奇,这个怎么实现?研究了一各个搜索引擎怎么传送关键字,找到了小窍门,于是乎,自家弄了一个百家搜索: 效果: 演示地址戳此:http://sousuodaquan.sinaapp.com/ ps:在列表中添加了糯米汇(http://www.nuomihui.com)的站内搜索,仅用于演示,别无它用,特此声明. HTML代码: <div class=&qu

在网页中添加google搜索

网页中插入谷歌搜索,至于怎么上谷歌,后面有时间会更,推荐百度 1 <form method="GET" action="http://www.google.com.hk/search" class="form-group">//name属性不能更改 否则无法提交问题跳转到检索的页面,而是直接调到Google搜索的主界面 2 <input type="text" class="form-control

spring boot使用guava缓存

1.pom中插入依赖: <!--guava缓存cache--> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>23.5-jre</version> </dependency> 2.在com.example.mapper.mybatisMap建立一个包cache,在cac

Spring源码学习:第1步--在Spring源码中添加最简单的Demo代码

为了最大程度地贴近Spring源码并进行学习,一种比较直接的做法是:直接在Spring源码中加入Demo代码,并进行调试. 参照以前使用Spring的经验,Spring最简单的使用方法是:一个实体类.一个Xml配置文件.再加个测试方法.而对于脱离源码的使用,需要至少引入 spring-context 依赖.于是,猜想,在Spring源码中是否可以直接在 spring-context 模块中添加上述最简单的代码呢? 说干就干,在 spring-context 模块中新建一个实体类(Person,位

Spring Cloud微服务架构实现+Guava缓存+redis+数据库设计+微服务原理改造房产销售

Spring Cloud微服务架构实现+Guava缓存+redis+数据库设计+微服务原理改造房产销售 一.分布式服务框架的发展 1.1 第一代服务框架 代表:Dubbo(Java).Orleans(.Net)等 特点:和语言绑定紧密 1.2 第二代服务框架 代表:Spring Cloud等 现状:适合混合式开发(例如借助Steeltoe OSS可以让ASP.Net Core与Spring Cloud集成),正值当年 1.3 第三代服务框架 代表:Service Mesh(服务网格) => 例如

spring中的缓存--

1.spring从3.1开始支持缓存功能.spring 自带的缓存机制它只在方法上起作用,对于你使用其他持久化层的框架来讲,是没有影响的,相对来讲这种缓存方式还是不错的选择. 2.提供缓存的接口:org.springframework.cache.Cache :org.springframework.cache.CacheManager这两个接口都在context中,一个是用来提供缓存的,一个是用来提供管理缓存的. 3.缓存是使用键值对的形式存在的,对应Java中就要使用Map<K,V>这种数

step4-----&gt;往工程中添加Spring的子项目spring IO Platform-------&gt;通过maven添加相关框架(pom.xml)

添加Spring IO Platform的目的: 避免自己的project的外部依赖(external dependencies)之间产生版本冲突问题.更多详细信息参见:Spring IO Platform概述 具体操作步骤: step1,往自己的工程中添加Spring IO Platform 编写project的pom.xml,添加如下代码,引入Spring IO Platform <dependencyManagement> <dependencies> <depende

step4---&gt;往工程中添加Spring框架----&gt;修改maven的配置文件pom.xml,向工程中添加spring框架的某些模块

1.本文内容: 本文介绍使用maven向自己的项目中添加各种框架的方法,即如何配置maven的pom.xml来让maven帮助管理这些框架(包括Spring.SpringMVC.hibernate框架等等). 2.使用maven向自己的工程中添加框架: 2.1概述 若想使用maven向自己的工程中添加三方框架(如Spring.SpringMVC等),需要先确保你的工程是maven工程,如果你还不知道该如何在myeclipse中建立一个maven web project,请参考相关教程. 2.2使

Spring 中使用redis缓存方法记录

背景 在平时项目中,可能会有某个条件的查询,会多次进到db里面去查,这样就会重复的查询相同的数据,但是我们的数据又不是需要更改及显示的,这时候就可以用到 方法的缓存了.例如在我们调用微信小程序时,需要获取access_token,并且其有效时间为7200秒,过期后再次获取,我们就可以把获取access_token的方法作为 缓存.以下为我实现的过程记录. 1.重写 RedisSerializer 中的 serialize 和 deserialize 1 public class GenericF