Spring Cacheable

缓存已经在我们的系统中成为性能提升最重要的方式,页面级缓存、系统级缓存、数据缓存、数据库内置缓存等等一些列缓存操作,今天要告诉大家spring其实也提供缓存,当然它只支持单点缓存,所以被忽略,局限性比较大,其实N多种框架都是带有缓存。不过最近JavaOne最近一次的大会上,提到如何办到单机下性能最优化,其实包括国内点评网在内的以java为核心技术的互联网公司为了省成本,其实也在最大限度发挥单机的下java服务性能指标。

谈到spring的缓存想到的是两个注解@Cacheable and @CacheEvict

@Cacheable能够提供类级别以及颗粒度达到方法级别

类级别

@Cacheable(value = "employee")
public class EmployeeDAO {

  public Person findEmployee(String firstName, String surname, int age) {
@Cacheable(value = "employee", key = "#surname")
public Person findEmployeeBySurname(String firstName, String surname, int age) {

  return new Person(firstName, surname, age);
}
  return new Person(firstName, surname, age); } public Person findAnotherEmployee(String firstName, String surname, int age) { return new Person(firstName, surname, age); } }

 上述的Person即将被cache

你可以同SpEL的方式指定cache的key值,学习SpEL可以查看我的另一篇博文 http://cywhoyi.iteye.com/blog/1945771

 

@Cacheable(value = "employee", condition = "#age < 25")
public Person findEmployeeByAge(String firstName, String surname, int age) {

  return new Person(firstName, surname, age);
}

 其实这样的方式非常简单,比其一般的我们设计SimpleCache,采用LRU、FIFO的算法控制缓存时效加上弱引用对象而减少内存的压榨来得更加便捷。

接下来让我们进行比较测试

@Test
public void testCache() {

  Person employee1 = instance.findEmployee("John", "Smith", 22);
  Person employee2 = instance.findEmployee("John", "Smith", 22);

  assertEquals(employee1, employee2);
}

 true,下面的employee2就是来源于cache

@Test
public void testCacheWithAgeAsCondition2() {

  Person employee1 = instance.findEmployeeByAge("John", "Smith", 30);
  Person employee2 = instance.findEmployeeByAge("John", "Smith", 30);

  assertFalse(employee1 == employee2);
}

 因为都大于22所以来源于的对象都是新产生的

@Test
public void testCacheWithAgeAsCondition() {

  Person employee1 = instance.findEmployeeByAge("John", "Smith", 22);
  Person employee2 = instance.findEmployeeByAge("John", "Smith", 22);

  assertEquals(employee1, employee2);
}

 

都是同一个对象

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值