在Spring中,@Cacheable
注解用于將方法的返回值緩存起來,當相同的參數(shù)再次調(diào)用該方法時,直接從緩存中獲取結(jié)果,而不再執(zhí)行方法體。
要使用@Cacheable
注解,需要進行以下幾步操作:
<cache:annotation-driven/>
標簽。@Cacheable
注解,指定緩存的名稱(如果沒有指定名稱,默認使用方法的全限定名)、緩存的鍵(可通過SpEL表達式指定,如@Cacheable(key = "#param")
)等參數(shù)。例如,考慮以下的UserService接口和實現(xiàn)類:
public interface UserService {
User getUserById(long id);
}
@Service
public class UserServiceImpl implements UserService {
@Override
@Cacheable(value = "userCache", key = "#id")
public User getUserById(long id) {
// 從數(shù)據(jù)庫中獲取用戶數(shù)據(jù)
// ...
return user;
}
}
在上述示例中,@Cacheable
注解被用于getUserById()
方法上,指定了緩存的名稱為"userCache",緩存的鍵為id
參數(shù)。當getUserById()
方法被調(diào)用時,如果緩存中已經(jīng)存在了指定鍵的結(jié)果,那么直接從緩存中獲取結(jié)果,否則執(zhí)行方法體,并將結(jié)果放入緩存中。
需要注意的是,為了使@Cacheable
注解起作用,還需要在Spring配置文件中配置緩存管理器,例如使用SimpleCacheManager
:
<bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager">
<property name="caches">
<set>
<bean class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean" p:name="userCache"/>
</set>
</property>
</bean>
上述配置創(chuàng)建了一個名為"userCache"的緩存,使用ConcurrentMapCacheFactoryBean
作為緩存實現(xiàn)。你也可以使用其他的緩存實現(xiàn),如Ehcache、Redis等。
這樣,當多次調(diào)用getUserById()
方法時,如果相同的id參數(shù)被傳遞進來,方法的返回值將直接從緩存中獲取,而不再執(zhí)行方法體,提高了系統(tǒng)的性能。