Spring实战教程 | 第八篇:Spring缓存---创建第一个缓存应用程序

介绍

缓存是一种存储机制,它将数据保存在某个地方,并以一种更快的方式为日后的请求提供服务,在应用程序中使用缓存机制,可以避免方法的多次执行,可以根据所提供的输入值对方法的结果数据进行缓存
通过使用AOP原则,对方法进行编织,如果已经为提供的参数执行过,那么不必执行实际方法就可以返回被缓存的结果,所以需要为应用程序的所有类生成代理类,并使用缓存注解对类的方法进行标记

创建第一个缓存应用程序

(1)创建一个空Maven,添加以下依赖,缓存注金额之类的类位于spring-contextJAR中

<dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>4.1.6.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>4.1.6.RELEASE</version>
    </dependency>

(2)在com.wiley.beginningspring.ch10包中创建域类User

public class User {
    private int id;
    private String name;

    public User(int id, String name) {
        this.id = id;
        this.name = name;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}

(3)在com.wiley.beginningspring.ch10包中创建

public class UserService {
    private Map<Integer,User> users=new HashMap<Integer, User>();
    {
        users.put(1,new User(1,"Kenan"));
        users.put(2,new User(2,"Mert"));
    }
    @Cacheable(value="users")//根据方法参数对方法的返回值进行缓存
    public User getUser(int id)
    {
        System.out.println("id = [" + id + "]");
        return users.get(id);
    }
}

(4)在src/main/resources/文件中创建applicationContext.xml配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:cache="http://www.springframework.org/schema/cache"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd">
  <!--支持cache注解-->
    <cache:annotation-driven/>

    <bean id="usersService" class="com.wiley.beginningspring.ch10.UserService">
    </bean>
    <!--定义缓存管理器-->
 <bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager">
 <!--定义缓存区域,根据命名约定,将缓存区域与所使用的注解绑定起来-->
        <property name="caches">
            <set>
                <bean id="users" class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean"></bean>
            </set>
        </property>
    </bean>
</beans>

(5)测试

public class Main {
    public static void main(String[] args) {
        ApplicationContext context=
                new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService userService=context.getBean(UserService.class);
        User userFetch1=userService.getUser(1);// 第一次执行etUser方法返回
        System.out.println(userFetch1);

        User userFetch2=userService.getUser(2);
        System.out.println(userFetch2);
        User userFetch3=userService.getUser(1);// 第二次直接从缓存返回
        System.out.println(userFetch3);
        User userFetch4=userService.getUser(1);// 第三次也是直接从缓存返回
        System.out.println(userFetch4);
    }
}

运行结果
这里写图片描述

使用不同的ID/name显式地指定缓存管理器

<cache:annotation-driven cache-manager="myCacheManager"/>
    <bean id="myCacheManager" class="org.springframework.cache.support.SimpleCacheManager">

    </bean>

使用注解配置缓存对象

除了xml配置还可以使用注解配置

@Configuration
@ComponentScan(basePackages = {"com.wiley.beginningspring.ch10"})
@EnableCaching
public class ApplicationConfig {
    @Bean
    public CacheManager cacheManager()
    {
        //创建一个SimpleCacheManager并使用了名称users设置了新ConcurrentMapCache
        SimpleCacheManager cacheManager=new SimpleCacheManager();
        cacheManager.setCaches(Arrays.asList(new ConcurrentMapCache(
                "users"
        )));
        return cacheManager;
    }
}

测试

public class Main {
    public static void main(String[] args) {
//        ApplicationContext context=
//                new ClassPathXmlApplicationContext("applicationContext.xml");
        ApplicationContext context=new AnnotationConfigApplicationContext(ApplicationConfig.class);
        UserService userService=context.getBean(UserService.class);
        User userFetch1=userService.getUser(1);// 第一次执行etUser方法返回
        System.out.println(userFetch1);

        User userFetch2=userService.getUser(2);
        System.out.println(userFetch2);
        User userFetch3=userService.getUser(1);// 第二次直接从缓存返回
        System.out.println(userFetch3);
        User userFetch4=userService.getUser(1);// 第三次也是直接从缓存返回
        System.out.println(userFetch4);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值