关闭

Spring Cache 使用

标签: spring cachecachespring
400人阅读 评论(0) 收藏 举报
分类:

1.Maven配置项目所需要的JAR包

<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.zhaochao</groupId>
	<artifactId>Demo</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>Demo</name>
	<url>http://maven.apache.org</url>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<org.springframework.version>4.1.6.RELEASE</org.springframework.version>
		<project.version>1.0.0-SNAPSHOT</project.version>
		<junit.version>4.12</junit.version>

	</properties>

	<dependencies>
		<!-- junit 测试包 -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>${junit.version}</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${org.springframework.version}</version>
		</dependency>
		<!-- Bean Factory and JavaBeans utilities (depends on spring-core) Define this if you use Spring Bean APIs (org.springframework.beans.*) -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-beans</artifactId>
			<version>${org.springframework.version}</version>
		</dependency>

		<!-- Aspect Oriented Programming (AOP) Framework (depends on spring-core, spring-beans) Define this if you use Spring AOP APIs (org.springframework.aop.*) -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aop</artifactId>
			<version>${org.springframework.version}</version>
		</dependency>

		<!-- Application Context (depends on spring-core, spring-expression, spring-aop, spring-beans) This is the central artifact for Spring's Dependency Injection Container and is generally always defined -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${org.springframework.version}</version>
		</dependency>


		<!-- Support for testing Spring applications with tools such as JUnit and TestNG This artifact is generally always defined with a 'test' scope for the integration testing framework and unit testing stubs -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>${org.springframework.version}</version>
			<scope>test</scope>
		</dependency>





	</dependencies>
</project>

2.Spring配置


<?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:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:p="http://www.springframework.org/schema/p" xmlns:cache="http://www.springframework.org/schema/cache"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
		http://www.springframework.org/schema/cache
        http://www.springframework.org/schema/cache/spring-cache.xsd"
	default-autowire="byType">

	<context:annotation-config />
	<context:component-scan base-package="com.zhaochao.service" />
	<cache:annotation-driven cache-manager="cacheManager" />
	<!--spring 自带CachedManager    -->
	<bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager">
		<property name="caches">
			<set>
				<bean class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean">
					<property name="name" value="userCache" />
				</bean>
			</set>
		</property>
	</bean>


</beans>

3.定义用户类


package com.zhaochao.service;

public class User {
	private Integer id;
	private String  name;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	@Override
	public String toString() {
		return "User [id=" + id + ", name=" + name + ", age=" + age + "]";
	}
	public void setName(String name) {
		this.name = name;
	}
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	private Integer age;
}

4.用户服务类

package com.zhaochao.service;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service("userService")
public class UserService {

	// 查询缓存
	@Cacheable(value = "userCache", key = "#userId")
	public User getUserById(Integer userId) {
		System.err.println("===queryUserById from db======");
		User u=new User();
		u.setId(userId);
		u.setName("赵云");
		u.setAge(20);
		return u;
	}
	// 删除缓存
	@CacheEvict(value = "userCache", condition ="#userId <=2 ")
	public String deleteUserById(int userId) {
	
		System.err.println("===deleteUserById===="+userId+"===");
		return String.valueOf(userId);
	}
	// 更新缓存
	@CachePut(value = "userCache", key = "#userId")
	public User updateUserById(Integer userId) {
		System.err.println("updateUserById ======== in DB =========");
		User u=new User();
		u.setId(userId);
		u.setName("马超");
		u.setAge(20);
		return u;
	}

}

5.测试类

package com.zhaochao.service.test;

import org.junit.Test;


import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.zhaochao.service.UserService;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:spring-common.xml")
public class UserServiceTest {
	@Autowired
	private UserService userService;

	@Test
	public void testCache(){
		//首次查询
		System.err.println(userService.getUserById(1));
		System.err.println(userService.getUserById(2));
		System.err.println(userService.getUserById(3));
		System.err.println(userService.getUserById(4));
		System.err.println();
		//缓存查询
		System.err.println(userService.getUserById(1));
		System.err.println(userService.getUserById(2));
		System.err.println();
		//更新缓存
		System.err.println(userService.updateUserById(1));
		System.err.println(userService.getUserById(1));
		System.err.println();
		//删除缓存中userId<2
		System.err.println(userService.deleteUserById(1));
		System.err.println(userService.deleteUserById(4));
		System.err.println(userService.getUserById(1));
		System.err.println(userService.getUserById(4));
		
		
	}
}

6.结果




7.自定义缓存将spring 配置改成

<?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:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:p="http://www.springframework.org/schema/p" xmlns:cache="http://www.springframework.org/schema/cache"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
		http://www.springframework.org/schema/cache
        http://www.springframework.org/schema/cache/spring-cache.xsd"
	default-autowire="byType">

	<context:annotation-config />
	<context:component-scan base-package="com.zhaochao.service" />
	<cache:annotation-driven cache-manager="cacheManager" />

  <!-- 自定义CachedManager  -->
	<bean id="cacheManager" class="com.zhaochao.service.MyCacheManager">
		<property name="caches">
			<set>
				<bean class="com.zhaochao.service.MyCache" p:name="userCache" />
			</set>
		</property>
	</bean>

</beans>

8.MyCache


package com.zhaochao.service;

import java.util.HashMap;
import java.util.Map;
import org.springframework.cache.Cache;
import org.springframework.cache.support.SimpleValueWrapper;

public class MyCache implements Cache {
	private String name;

	public void setName(String name) {
		this.name = name;
	}
	private Map<Integer, User> store = new HashMap<Integer, User>();
	public MyCache() {

	}
	public MyCache(String name) {
		this.name = name;
	}
	public String getName() {
		return this.name;
	}

	public Object getNativeCache() {
		return null;
	}
	public ValueWrapper get(Object key) {
		ValueWrapper result = null;
		User thevalue = store.get(key);
		if (thevalue != null) {
			result = new SimpleValueWrapper(thevalue);
		}
		return result;
	}
	public <User> User get(Object key, Class<User> type) {
		return (User) store.get(key);
	}
	public void put(Object key, Object value) {
		store.put((Integer) key, (User) value);
	}
	public ValueWrapper putIfAbsent(Object key, Object value) {
		return null;
	}

	public void evict(Object key) {
		store.remove((String) key);
	}
	public void clear() {
		store.clear();
	}

}

9.MyCacheManager

package com.zhaochao.service;

import java.util.Collection;

import org.springframework.cache.support.AbstractCacheManager;

public class MyCacheManager extends AbstractCacheManager {
	private Collection<? extends MyCache> caches;

	public void setCaches(Collection<? extends MyCache> caches) {
		this.caches = caches;
	}
	@Override
	protected Collection<? extends MyCache> loadCaches() {
		return this.caches;
	}

}



1
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:334516次
    • 积分:4876
    • 等级:
    • 排名:第5827名
    • 原创:154篇
    • 转载:7篇
    • 译文:0篇
    • 评论:110条
    最新评论