Spring Cache 使用

本文介绍如何使用Maven管理项目的依赖,并结合Spring框架实现缓存管理。具体包括Maven配置文件详解、Spring配置说明、自定义缓存实现等。通过示例展示了缓存查询、更新和删除的操作。

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

}



转载于:https://www.cnblogs.com/whzhaochao/p/5023405.html

Spring CacheSpring框架提供的一种缓存机制,用于提高应用程序的性能和响应速度。通过使用Spring Cache,可以将方法的返回值缓存起来,当下次调用相同的方法时,可以直接从缓存中获取结果,而不需要再执行方法的逻辑。 在使用Spring Cache时,需要进行一些配置。首先,需要添加Redis的配置信息,包括缓存类型、缓存过期时间、缓存键的前缀等。可以通过设置`spring.cache.type`为`redis`来指定使用Redis作为缓存类型。可以使用`spring.cache.redis.time-to-live`设置缓存的过期时间,单位为毫秒。可以使用`spring.cache.redis.key-prefix`设置缓存键的前缀,如果不指定前缀,则默认使用缓存的名字作为前缀。可以使用`spring.cache.redis.use-key-prefix`设置是否使用前缀,默认为true。可以使用`spring.cache.redis.cache-null-values`设置是否缓存空值,以防止缓存穿透。 另外,Spring Cache还支持使用JCache(JSR-107)注解来简化开发。从Spring 3.1开始,定义了`org.springframework.cache.Cache`和`org.springframework.cache.CacheManager`接口来统一不同的缓存技术。 在使用Spring Cache时,可以通过在方法上添加`@Cacheable`注解来启用缓存功能。当调用带有`@Cacheable`注解的方法时,Spring会首先检查缓存中是否存在相应的结果,如果存在,则直接返回缓存中的结果,如果不存在,则执行方法的逻辑,并将结果存入缓存中。 总结起来,使用Spring Cache可以通过配置Redis等缓存信息,并在方法上添加`@Cacheable`注解来实现缓存功能,提高应用程序的性能和响应速度。 #### 引用[.reference_title] - *1* [SpringCache使用](https://blog.youkuaiyun.com/ABestRookie/article/details/121297482)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* *3* [springcache使用详解(使用redis做分布式缓存)](https://blog.youkuaiyun.com/A_art_xiang/article/details/125580962)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值