RELATEED CONSULTING
相关咨询
选择下列产品马上在线沟通
服务时间:8:30-17:00
你可能遇到了下面的问题
关闭右侧工具栏

新闻中心

这里有您想知道的互联网营销解决方案
Spring中怎么实现方法级别缓存

Spring中怎么实现方法级别缓存,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。

目前成都创新互联公司已为近1000家的企业提供了网站建设、域名、雅安服务器托管、网站托管维护、企业网站设计、双台子网站维护等服务,公司将坚持客户导向、应用为本的策略,正道将秉承"和谐、参与、激情"的文化,与客户和合作伙伴齐心协力一起成长,共同发展。

一 配置文件

             

二 属性文件

           

三 领域模型

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()查询方法--falsetrue

看完上述内容,你们掌握Spring中怎么实现方法级别缓存的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注创新互联行业资讯频道,感谢各位的阅读!


当前题目:Spring中怎么实现方法级别缓存
链接地址:http://scyingshan.cn/article/pchcpi.html