LiuShuaiDong:SpringBoot之整合Ehcache2.x

一、引入依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
        </dependency>

        <dependency>
            <groupId>net.sf.ehcache</groupId>
            <artifactId>ehcache</artifactId>
        </dependency>

二、添加缓存配置文件(将ehcache.xml文件复制到项目的resources目录下)

下载地址:https://www.ehcache.org/

ehcache文件位置:code-samples/src/main/resources/xml/

也可用下面代码

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="ehcache.xsd"
         updateCheck="true" monitoring="autodetect"
         dynamicConfig="true">

    
    <diskStore path="java.io.tmpdir"/>

    

    <transactionManagerLookup class="net.sf.ehcache.transaction.manager.DefaultTransactionManagerLookup"
                              properties="jndiName=java:/TransactionManager" propertySeparator=";"/>



    <cacheManagerEventListenerFactory class="" properties=""/>



    <cacheManagerPeerProviderFactory
            class="net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory"
            properties="peerDiscovery=automatic,
                        multicastGroupAddress=230.0.0.1,
                        multicastGroupPort=4446, timeToLive=1"
            propertySeparator=","
            />



    <cacheManagerPeerListenerFactory
            class="net.sf.ehcache.distribution.RMICacheManagerPeerListenerFactory"/>


    <defaultCache
            maxEntriesLocalHeap="10000"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            diskSpoolBufferSizeMB="30"
            maxEntriesLocalDisk="10000000"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU">
        <persistence strategy="localTempSwap"/>
    </defaultCache>

    <cache name="user_cache"
           maxEntriesLocalHeap="10000"
           maxEntriesLocalDisk="1000"
           eternal="false"
           diskSpoolBufferSizeMB="20"
           timeToIdleSeconds="300"
           timeToLiveSeconds="600"
           memoryStoreEvictionPolicy="LFU"
           transactionalMode="off">
        <persistence strategy="localTempSwap"/>
    </cache>


    <cache name="sampleCache2"
           maxEntriesLocalHeap="1000"
           eternal="true"
           memoryStoreEvictionPolicy="FIFO"
            />


    <cache name="sampleCache3"
           maxEntriesLocalHeap="500"
           eternal="false"
           overflowToDisk="true"
           diskPersistent="true"
           timeToIdleSeconds="300"
           timeToLiveSeconds="600"
           diskExpiryThreadIntervalSeconds="1"
           memoryStoreEvictionPolicy="LFU">
    </cache>


    <cache name="sampleReplicatedCache1"
           maxEntriesLocalHeap="10"
           eternal="false"
           timeToIdleSeconds="100"
           timeToLiveSeconds="100">

        <cacheEventListenerFactory
                class="net.sf.ehcache.distribution.RMICacheReplicatorFactory"/>
        <bootstrapCacheLoaderFactory
                class="net.sf.ehcache.distribution.RMIBootstrapCacheLoaderFactory"/>
    </cache>


    <cache name="sampleRepicatedCache2"
           maxEntriesLocalHeap="10"
           eternal="false"
           timeToIdleSeconds="100"
           timeToLiveSeconds="100">
        <cacheEventListenerFactory
                class="net.sf.ehcache.distribution.RMICacheReplicatorFactory"
                properties="replicateAsynchronously=false, replicatePuts=false,
                            replicatePutsViaCopy=false, replicateUpdates=true,
                            replicateUpdatesViaCopy=true, replicateRemovals=false"/>
    </cache>

    <cache name="sampleReplicatedCache3"
           maxEntriesLocalHeap="10"
           eternal="false"
           timeToIdleSeconds="100"
           timeToLiveSeconds="100">
        <cacheEventListenerFactory
                class="net.sf.ehcache.distribution.RMICacheReplicatorFactory"
                properties="asynchronousReplicationIntervalMillis=200"/>
        <persistence strategy="localTempSwap"/>
    </cache>

</ehcache>

三、编写模拟Dao层类

其中@CacheConfig中的name要与配置文件中cache的那么一样

@Repository
@CacheConfig(cacheNames = "user_cache")//缓存名
public class UserDao {
    
    @Cacheable//下面方法进行缓存,缓存的key为参数id,缓存内容为返回的结果user
    public User getUserById(Integer id) {
        System.out.println("getUserById");
        User user = new User();
        user.setId(id);
        user.setUsername("刘林栋");
        user.setPhone("135+145454");
        user.setAge(18);
        return user;
    }


    @CachePut(key = "#user1.id")//更新缓存,更新所需的key为参数user1.id,内容为返回的结果
    public User putUser(User user1) {
        System.out.println("put");
        user1.setUsername("zst");
        return user1;
    }

    @CacheEvict(key = "#id1")//删除缓存,根据key删除(key为参数id1)
    public void deleteUser(Integer id1) {
        System.out.println("delete");
    }

}

四、编写测试类

@SpringBootTest
class AlltestApplicationTests {

    @Autowired
    UserDao userDao;

    @Test
    public void test() {
        //第一次执行getUserById方法,将结果写进内存
        userDao.getUserById(1);

        //再次运行此方法不执行,直接从内存中拿结果
        userDao.getUserById(1);

        //第一次执行deleteUser方法,删除key为1的缓存
        userDao.deleteUser(1);

        //因为已经删除了key为1的缓存,所以执行此方法时进入方法运行
        User user = userDao.getUserById(1);

        //输出user的信息
        System.out.println(user);

        User u = new User();

        u.setId(1);

        //将u(id=1)传给putUser方法,方法体为setUsername=zst
        userDao.putUser(u);

        //已经存在key为1的缓存,直接读缓存,不进入方法
        User u2 = userDao.getUserById(1);

        System.out.println(u2);

    }



}

五、结果显示

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值