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);
}

 

都是同一个对象

你可能感兴趣的:(JavaGeeker,opensource,spring,Performance)