Spring缓存

对服务层方法进行缓存

新建maven项目,添加依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.spring.cache</groupId>
    <artifactId>spring.cache</artifactId>
    <version>1.0-SNAPSHOT</version>
<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>4.0.5.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>4.0.5.RELEASE</version>
    </dependency>
</dependencies>

</project>

新建域类User

public class User {

    private int id;

    private String name;

    public User(int id,String name){

        this.id = id;

        this.name = name;

    }

    public String toString(){

        return "User{id = " + id +", name = " + name + " }";

    }

}

新建服务层类userService

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("User with id " + id + " requested.");

        return users.get(id);

    }

}

在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-4.0.xsd">

    <cache:annotation-driven/>

    <bean id="userService" class="com.beginning.UserService"/>

    <bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager">

        <property name="caches">

            <set>

                <bean id="users" class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean"/>

            </set>

        </property>

    </bean>

</beans>

在main方法中获取bean

public class Main {

    public static void main(String[] args) {

        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

        UserService userService = context.getBean(UserService.class);

        User user1 = userService.getUser(1);

        System.out.println(user1);



        User user2 = userService.getUser(1);

        System.out.println(user2);

    }

}

运行截图

uploading.4e448015.gif转存失败重新上传取消uploading.4e448015.gif转存失败重新上传取消

实例说明

缓存的目的在于将被缓存的方法的运行结果缓存起来,通过相同的方法参数直接调用结果,可以提高性能。

对重复使用的一下方法用spring提供的缓存十分有用。

在UserService的getUser方法上使用@Cacheable注解,表明将根据方法参数对方法的返回值进行缓存。

在定义应用程序配置文件时,首先声明<cache:annotation-driven/>

最后实现cache管理器

缓存管理器

@Cacheable

@CacheEvict

@CachePut

@Caching

启动缓存存储器

修改UserService类

@Service

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

    }

    @Autowired

    private CacheManager cacheManager;





    @Cacheable(value = "users")

    public User getUser(int id){

        System.out.println("User with id " + id + " requested.");

        return users.get(id);

    }

    @PostConstruct

    public void setup(){

        Cache usersCache = cacheManager.getCache("users");

        for(Integer key : users.keySet()){

            usersCache.put(key,users.get((key)));

        }

    }

}

创建ApplicationConfig类

@Configuration

@ComponentScan(basePackages = {"com.beginning.bean"})

@EnableCaching

public class ApplicationConfig {

    @Bean

    public CacheManager cacheManager(){

        SimpleCacheManager cacheManager = new SimpleCacheManager();

        cacheManager.setCaches(Arrays.asList(new ConcurrentMapCache("users")));

        return cacheManager;

    }

}

执行main方法

与Ehcache缓存管理器相集成

添加依赖

<dependency>

    <groupId>org.springframework</groupId>

    <artifactId>spring-context-support</artifactId>

    <version>4.0.5.RELEASE</version>

</dependency>

<dependency>

    <groupId>net.sf.ehcache</groupId>

    <artifactId>ehcache</artifactId>

    <version>2.8.3</version>

</dependency>

修改User域类

public class User {

    private int id;

    private String name;

    private String phoneNumber;

    private int age;

    public User(int id,String name,String p,int age){

        this.id = id;

        this.name = name;

        this.phoneNumber = p;

        this.age = age;

    }



    public int getAge() {

        return age;

    }



    public int getId() {

        return id;

    }



    public String toString(){

        return "User{id = " + id +", name = " + name + " }";

    }

}

修改UserService类

public class UserService {

    private Map<Integer, User> users = new HashMap<Integer, User>();

    {

        users.put(1,new User(1,"Kenan","5555555",38));

        users.put(2,new User(2,"Mert","4353453453",20));

    }





    @Cacheable(value = "users",condition = "#user.age < 35")

    public User getUser(User user){

        System.out.println("User with id " + user.getId() + " requested.");

        return users.get(user.getId());

    }

}

修改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-4.0.xsd">

<cache:annotation-driven/>

<bean id="userService" class="com.beginning.bean.UserService"/>

<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">

    <property name="cacheManager" ref="ehcache"/>

</bean>

    <bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">

        <property name="configLocation" value="classpath:ehcache.xml" />

    </bean>

</beans>

在src/main/resources中创建ehcache.xml文件

<ehcache>

    <cache name="users" maxElementsInMemory="1000"/>

</ehcache>

创建Main方法

public class Main {

    public static void main(String[] args) {

        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

        UserService userService = context.getBean(UserService.class);

        User user1 = new User(1,"Kenan","5555555",38);

        User userFetch1 = userService.getUser(user1);

        System.out.println(userFetch1);

        User userFetch2 = userService.getUser(user1);

        System.out.println(userFetch1);



        User user2 = new User(2,"Mert","4353453453",20);

        User userFetch3 = userService.getUser(user2);

        System.out.println(userFetch3);

        User userFetch4 = userService.getUser(user2);

        System.out.println(userFetch4);

    }

}

运行结果

uploading.4e448015.gif转存失败重新上传取消uploading.4e448015.gif转存失败重新上传取消

实例说明

通过使用spring-context-support工件,spring包含了Ehache缓存管理器,从而便于集成。

@Cacheable注解包含了条件特性,表明只有年龄小于35岁的用户才会被缓存。

在配置文件中配置新的缓存存储管理器和存储器。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值