Spring实战之方法级别缓存用法示例

本文实例讲述了Spring实战之方法级别缓存用法。分享给大家供大家参考,具体如下:

一 配置文件

<?xml version="1.0" encoding="GBK"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:p="http://www.springframework.org/schema/p"
   xmlns:cache="http://www.springframework.org/schema/cache"
   xmlns:context="http://www.springframework.org/schema/context"
   xsi:schemaLocation="http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
   http://www.springframework.org/schema/cache
   http://www.springframework.org/schema/cache/spring-cache-4.0.xsd
   http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context-4.0.xsd">
   <context:component-scan
      base-package="org.crazyit.app.service" />
   <cache:annotation-driven
      cache-manager="cacheManager" />
   <!-- 配置EhCache的CacheManager 通过configLocation指定ehcache.xml文件的位置 -->
   <bean id="ehCacheManager"
      class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"
      p:configLocation="classpath:ehcache.xml" p:shared="false" />
   <!-- 配置基于EhCache的缓存管理器 并将EhCache的CacheManager注入该缓存管理器Bean -->
   <bean id="cacheManager"
      class="org.springframework.cache.ehcache.EhCacheCacheManager"
      p:cacheManager-ref="ehCacheManager">
   </bean>
</beans>

二 属性文件

<?xml version="1.0" encoding="gbk"?>
<ehcache>
  <diskStore path="java.io.tmpdir" />
   <!-- 配置默认的缓存区 -->
  <defaultCache
    maxElementsInMemory="10000"
    eternal="false"
    timeToIdleSeconds="120"
    timeToLiveSeconds="120"
    maxElementsOnDisk="10000000"
    diskExpiryThreadIntervalSeconds="120"
    memoryStoreEvictionPolicy="LRU"/>
   <!-- 配置名为users1的缓存区 -->
  <cache name="users1"
    maxElementsInMemory="10000"
    eternal="false"
    overflowToDisk="true"
    timeToIdleSeconds="300"
    timeToLiveSeconds="600" />
  <cache name="users2"
    maxElementsInMemory="10000"
    eternal="false"
    overflowToDisk="true"
    timeToIdleSeconds="300"
    timeToLiveSeconds="600" />
</ehcache>

三 领域模型

package org.crazyit.app.domain;
public class User
{
   private String name;
   private int age;
   public User()
   {}
   public User(String name, int age)
   {
      super();
      this.name = name;
      this.age = age;
   }
   public String getName()
   {
      return name;
   }
   public void setName(String name)
   {
      this.name = name;
   }
   public int getAge()
   {
      return age;
   }
   public void setAge(int age)
   {
      this.age = age;
   }
}

四 Service

1 接口类

package org.crazyit.app.service;
import org.crazyit.app.domain.User;
public interface UserService
{
   User getUsersByNameAndAge(String name, int age);
   User getAnotherUser(String name, int age);
}

2 实现类

package org.crazyit.app.service.impl;
import org.crazyit.app.service.UserService;
import org.crazyit.app.domain.User;
import org.springframework.stereotype.Service;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.annotation.Scope;
@Service("userService")
public class UserServiceImpl implements UserService
{
  @Cacheable(value = "users1")
  public User getUsersByNameAndAge(String name, int age)
  {
    System.out.println("--正在执行findUsersByNameAndAge()查询方法--");
    return new User(name, age);
  }
  @Cacheable(value = "users2")
  public User getAnotherUser(String name, int age)
  {
    System.out.println("--正在执行findAnotherUser()查询方法--");
    return new User(name, age);
  }
}

五 测试类

package lee;
import org.crazyit.app.service.UserService;
import org.crazyit.app.domain.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringTest
{
  public static void main(String[] args)
  {
    ApplicationContext ctx =
      new ClassPathXmlApplicationContext("beans.xml");
    UserService us = ctx.getBean("userService" , UserService.class);
    // 第一次调用us对象的方法时会执行该方法,并缓存方法的结果
    User u1 = us.getUsersByNameAndAge("孙悟空", 500);
    // 由于getAnotherUser()方法使用另一个缓存区,
    // 因此无法使用getUsersByNameAndAge()方法缓存区的数据。
    User u2 = us.getAnotherUser("孙悟空", 500);
    System.out.println(u1 == u2); // 输出false
    // getAnotherUser("孙悟空", 500)已经执行过一次,故下面代码使用缓存
    User u3 = us.getAnotherUser("孙悟空", 500);
    System.out.println(u2 == u3); // 输出true
  }
}

六 测试结果

--正在执行findUsersByNameAndAge()查询方法--
--正在执行findAnotherUser()查询方法--
false
true

更多关于java相关内容感兴趣的读者可查看本站专题:《Spring框架入门与进阶教程》、《Java数据结构与算法教程》、《Java操作DOM节点技巧总结》、《Java文件与目录操作技巧汇总》和《Java缓存操作技巧汇总》

希望本文所述对大家java程序设计有所帮助。

(0)

相关推荐

  • Spring实战之清除缓存操作示例

    本文实例讲述了Spring实战之清除缓存操作.分享给大家供大家参考,具体如下: 一 配置文件 <?xml version="1.0" encoding="GBK"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p=&

  • Spring Boot 基于注解的 Redis 缓存使用详解

    看文本之前,请先确定你看过上一篇文章<Spring Boot Redis 集成配置>并保证 Redis 集成后正常可用,因为本文是基于上文继续增加的代码. 一.创建 Caching 配置类 RedisKeys.Java package com.shanhy.example.redis; import java.util.HashMap; import java.util.Map; import javax.annotation.PostConstruct; import org.springf

  • 详解Spring缓存注解@Cacheable,@CachePut , @CacheEvict使用

    注释介绍 @Cacheable @Cacheable 的作用 主要针对方法配置,能够根据方法的请求参数对其结果进行缓存 @Cacheable 作用和配置方法 参数 解释 example value 缓存的名称,在 spring 配置文件中定义,必须指定至少一个 例如: @Cacheable(value="mycache") @Cacheable(value={"cache1","cache2"} key 缓存的 key,可以为空,如果指定要按照

  • Spring实战之缓存使用key操作示例

    本文实例讲述了Spring实战之缓存使用key操作.分享给大家供大家参考,具体如下: 一 配置文件 <?xml version="1.0" encoding="GBK"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:

  • spring结合redis如何实现数据的缓存

    1.实现目标 通过redis缓存数据.(目的不是加快查询的速度,而是减少数据库的负担) 2.所需jar包 注意:jdies和commons-pool两个jar的版本是有对应关系的,注意引入jar包是要配对使用,否则将会报错.因为commons-pooljar的目录根据版本的变化,目录结构会变.前面的版本是org.apache.pool,而后面的版本是org.apache.pool2... style="background-color: #0098dd; color: white; font-s

  • Redis整合Spring结合使用缓存实例

    一.Redis介绍 什么是Redis?       redis是一个key-value存储系统.和Memcached类似,它支持存储的value类型相对更多,包括string(字符串).list(链表).set(集合).zset(sorted set --有序集合)和hash(哈希类型).这些数据类型都支持push/pop.add/remove及取交集并集和差集及更丰富的操作,而且这些操作都是原子性的.在此基础上,redis支持各种不同方式的排序.与memcached一样,为了保证效率,数据都是

  • SpringBoot项目中使用redis缓存的方法步骤

    本文介绍了SpringBoot项目中使用redis缓存的方法步骤,分享给大家,具体如下: Spring Data Redis为我们封装了Redis客户端的各种操作,简化使用. - 当Redis当做数据库或者消息队列来操作时,我们一般使用RedisTemplate来操作 - 当Redis作为缓存使用时,我们可以将它作为Spring Cache的实现,直接通过注解使用 1.概述 在应用中有效的利用redis缓存可以很好的提升系统性能,特别是对于查询操作,可以有效的减少数据库压力. 具体的代码参照该

  • Spring Boot集成Ehcache缓存解决方式

    本次内容主要介绍基于Ehcache 3.0来快速实现Spring Boot应用程序的数据缓存功能.在Spring Boot应用程序中,我们可以通过Spring Caching来快速搞定数据缓存. 接下来我们将介绍如何在三步之内搞定 Spring Boot 缓存. 1. 创建一个Spring Boot工程 你所创建的Spring Boot应用程序的maven依赖文件至少应该是下面的样子: <?xml version="1.0" encoding="UTF-8"?

  • Spring实战之缓存使用condition操作示例

    本文实例讲述了Spring实战之缓存使用condition操作.分享给大家供大家参考,具体如下: 一 配置文件 <?xml version="1.0" encoding="GBK"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

  • Spring实战之类级别缓存实现与使用方法

    本文实例讲述了Spring实战之类级别缓存实现与使用方法.分享给大家供大家参考,具体如下: 一 配置文件 <?xml version="1.0" encoding="GBK"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xml

  • Spring Boot 中使用cache缓存的方法

    一.什么是缓存 Cache Cache 一词最早来自于CPU设计 当CPU要读取一个数据时,首先从CPU缓存中查找,找到就立即读取并送给CPU处理:没有找到,就从速率相对较慢的内存中读取并送给CPU处理,同时把这个数据所在的数据块调入缓存中,可以使得以后对整块数据的读取都从缓存中进行,不必再调用内存.正是这样的读取机制使CPU读取缓存的命中率非常高(大多数CPU可达90%左右),也就是说CPU下一次要读取的数据90%都在CPU缓存中,只有大约10%需要从内存读取.这大大节省了CPU直接读取内存的

随机推荐