文章來源地址http://www.zghlxwxcb.cn/news/detail-723632.html
主頁傳送門:?? 傳送
??Spring 提供了對緩存的支持,允許你將數(shù)據(jù)存儲在緩存中以提高應(yīng)用程序的性能。Spring 緩存抽象基于 Java Caching API,但提供了更簡單的編程模型和更高級的功能。
??Spring 集成緩存提供了一種方便的方式來使用緩存,從而提高應(yīng)用程序的性能。Spring 緩存抽象提供了通用的緩存支持,并集成了常見的緩存解決方案。
緩存接口
??Spring 的緩存 API 以注解方式提供。Spring緩存接口定義主要由org.springframework.cache.Cache和org.springframework.cache.CacheManager兩個接口完成。
-
org.springframework.cache.Cache:這個接口代表一個緩存組件,Spring框架通過這個接口與緩存交互。它有幾個重要的方法:
- String getName(): 返回緩存的名稱。
- Object get(Object key, Class<?> type): 根據(jù)key獲取緩存數(shù)據(jù),如果數(shù)據(jù)不存在,返回null。
- void put(Object key, Object value): 向緩存中添加數(shù)據(jù)。
- void evict(Object key): 根據(jù)key移除緩存數(shù)據(jù)。
- void clear(): 清空緩存。
-
org.springframework.cache.CacheManager:這個接口定義了如何獲取Cache實例。它有一個重要的方法:
- Cache getCache(String name): 根據(jù)緩存的名稱獲取Cache實例。
??Spring通過這些接口與各種緩存實現(xiàn)(如EhCache,Redis,Hazelcast等)進(jìn)行交互。要使用Spring的緩存功能,只需配置一個實現(xiàn)了CacheManager接口的Bean,然后在需要使用緩存的地方使用@Cacheable,@CacheEvict和@CachePut等注解即可。
開啟注解
??Spring 為緩存功能提供了注解功能,但是你必須啟動注解:
(1) 在 xml 中聲明
??使用cache:annotation-driven/<cache:annotation-driven cache-manager=“cacheManager”/>
(2) 使用標(biāo)記注解
?? 通過對一個類進(jìn)行注解修飾的方式在這個類中使用緩存注解。
范例如下:
@Configuration
@EnableCaching
public class AppConfig {
}
緩存注解使用
??Spring 對緩存的支持類似于對事務(wù)的支持。 首先使用注解標(biāo)記方法,相當(dāng)于定義了切點,然后使用 Aop 技術(shù)在這個方法的調(diào)用前、調(diào)用后獲取方法的入?yún)⒑头祷刂担M(jìn)而實現(xiàn)了緩存的邏輯。
@Cacheable
??表明所修飾的方法是可以緩存的:當(dāng)?shù)谝淮握{(diào)用這個方法時,它的結(jié)果會被緩存下來,在緩存的有效時間內(nèi),以后訪問這個方法都直接返回緩存結(jié)果,不再執(zhí)行方法中的代碼段。 這個注解可以用condition屬性來設(shè)置條件,如果不滿足條件,就不使用緩存能力,直接執(zhí)行方法。 可以使用key屬性來指定 key 的生成規(guī)則。
范例如下:
@Service
public class ExampleService {
@Cacheable("examples")
public String getExample(String key) {
// 模擬一個耗時操作
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "Example for " + key;
}
}
@CachePut
??與@Cacheable不同,@CachePut不僅會緩存方法的結(jié)果,還會執(zhí)行方法的代碼段。 當(dāng)一個方法被標(biāo)記為 @CachePut,Spring 會在該方法執(zhí)行后更新緩存。它支持的屬性和用法都與@Cacheable一致。
范例如下:
@Service
public class ExampleService {
@CachePut("examples")
public void updateExample(String key, String value) {
// 更新數(shù)據(jù)的操作
// ...
}
}
@CacheEvict
??與@Cacheable功能相反,@CacheEvict表明所修飾的方法是用來刪除失效或無用的緩存數(shù)據(jù)。當(dāng)一個方法被標(biāo)記為 @CacheEvict,Spring 會在該方法執(zhí)行后從緩存中移除相關(guān)的數(shù)據(jù)。
范例如下:
@Service
public class ExampleService {
@CacheEvict(value = "examples", key = "#id")
public void evictExample(String id) {
// 從緩存中移除數(shù)據(jù)的操作
// ...
}
}
@Cacheable、@CacheEvict和@CachePut使用方法的集中展示示例:
@Service
public class UserService {
// @Cacheable可以設(shè)置多個緩存,形式如:@Cacheable({"books", "isbns"})
@Cacheable(value={"users"}, key="#user.id")
public User findUser(User user) {
return findUserInDB(user.getId());
}
@Cacheable(value = "users", condition = "#user.getId() <= 2")
public User findUserInLimit(User user) {
return findUserInDB(user.getId());
}
@CachePut(value = "users", key = "#user.getId()")
public void updateUser(User user) {
updateUserInDB(user);
}
@CacheEvict(value = "users")
public void removeUser(User user) {
removeUserInDB(user.getId());
}
@CacheEvict(value = "users", allEntries = true)
public void clear() {
removeAllInDB();
}
}
@Caching
??如果需要使用同一個緩存注解(@Cacheable、@CacheEvict或@CachePut)多次修飾一個方法,就需要用到@Caching。
@Caching(evict = { @CacheEvict("primary"), @CacheEvict(cacheNames="secondary", key="#p0") })
public Book importBooks(String deposit, Date date)
@CacheConfig
??與前面的緩存注解不同,這是一個類級別的注解。 如果類的所有操作都是緩存操作,你可以使用@CacheConfig來指定類,省去一些配置。
@CacheConfig("books")
public class BookRepositoryImpl implements BookRepository {
@Cacheable
public Book findBook(ISBN isbn) {...}
}
緩存存儲
??Spring 允許通過配置方式接入多種不同的緩存存儲。用戶可以根據(jù)實際需要選擇。
不同的緩存存儲,具有不同的性能和特性。
使用 ConcurrentHashMap 作為緩存
示例配置:
<?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:cache="http://www.springframework.org/schema/cache" xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd">
<description>使用 ConcurrentHashMap 作為 Spring 緩存</description>
<context:component-scan base-package="io.github.dunwu.spring.cache"/>
<bean id="simpleCacheManager" class="org.springframework.cache.support.SimpleCacheManager">
<property name="caches">
<set>
<bean class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean" p:name="default"/>
<bean class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean" p:name="users"/>
</set>
</property>
</bean>
<cache:annotation-driven cache-manager="simpleCacheManager"/>
</beans>
使用 Ehcache 作為緩存
示例配置:
<?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: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/context https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd">
<description>使用 EhCache 作為 Spring 緩存</description>
<!--配置參考:https://docs.spring.io/spring/docs/current/spring-framework-reference/integration.html#cache-store-configuration-->
<context:component-scan base-package="io.github.dunwu.spring.cache"/>
<bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
<property name="configLocation" value="classpath:ehcache/ehcache.xml"/>
</bean>
<bean id="ehcacheCacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
<property name="cacheManager" ref="ehcache"/>
</bean>
<cache:annotation-driven cache-manager="ehcacheCacheManager"/>
</beans>
ehcache.xml 中的配置內(nèi)容完全符合 Ehcache 的官方配置標(biāo)準(zhǔn)。
使用 Caffeine 作為緩存
示例配置:
<?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: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/context https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd">
<description>使用 Caffeine 作為 Spring 緩存</description>
<!--配置參考:https://docs.spring.io/spring/docs/current/spring-framework-reference/integration.html#cache-store-configuration-->
<context:component-scan base-package="io.github.dunwu.spring.cache"/>
<bean id="caffeineCacheManager" class="org.springframework.cache.caffeine.CaffeineCacheManager"/>
<cache:annotation-driven cache-manager="caffeineCacheManager"/>
</beans>
參考資料
Spring 官方文檔文章來源:http://www.zghlxwxcb.cn/news/detail-723632.html
如果喜歡的話,歡迎 ??關(guān)注 ??點贊 ??評論 ??收藏 ??一起討論 你的支持就是我??創(chuàng)作的動力! ??????
到了這里,關(guān)于輕松搞定Spring集成緩存,讓你的應(yīng)用程序飛起來!的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!