整合@Cache 和 Redis
對(duì)于緩存聲明,spring的緩存提供了一組java注解:
@Cacheable:觸發(fā)緩存寫入。
@CacheEvict:觸發(fā)緩存清除。
@CachePut:更新緩存(不會(huì)影響到方法的運(yùn)行)。
@Caching:重新組合要應(yīng)用于方法的多個(gè)緩存操作。
@CacheConfig:設(shè)置類級(jí)別上共享的一些常見緩存設(shè)置。
@Cacheable注解
顧名思義,@Cacheable可以用來進(jìn)行緩存的寫入,將結(jié)果存儲(chǔ)在緩存中,以便于在后續(xù)調(diào)用的時(shí)候可以直接返回緩存中的值,而不必再執(zhí)行實(shí)際的方法。最簡單的使用方式,注解名稱=緩存名稱,使用例子如下:
@Cacheable("books")
public Book findBook(ISBN isbn) {...}一個(gè)方法可以對(duì)應(yīng)兩個(gè)緩存名稱,如下:
@Cacheable({"books", "isbns"})
public Book findBook(ISBN isbn) {...} @Cacheable的緩存名稱是可以配置動(dòng)態(tài)參數(shù)的,比如選擇傳入的參數(shù),如下: (以下示例是使用SpEL聲明,如果您不熟悉SpEL,可以閱讀Spring Expression Language)
@Cacheable(cacheNames="books", key="#isbn")
public Book findBook(ISBN isbn, boolean checkWarehouse, boolean includeUsed)
@Cacheable(cacheNames="books", key="#isbn.rawNumber")
public Book findBook(ISBN isbn, boolean checkWarehouse, boolean includeUsed)
@Cacheable(cacheNames="books", key="T(someType).hash(#isbn)")
public Book findBook(ISBN isbn, boolean checkWarehouse, boolean includeUsed)@Cacheable還可以設(shè)置根據(jù)條件判斷是否需要緩存
condition:取決于給定的參數(shù)是否滿足條件
unless:取決于返回值是否滿足條件
以下是一個(gè)簡單的例子:
@Cacheable(cacheNames="book", condition="#name.length() < 32")
public Book findBook(String name)
@Cacheable(cacheNames="book", condition="#name.length() < 32", unless="#result.hardback")
public Book findBook(String name) @Cacheable還可以設(shè)置:keyGenerator(指定key自動(dòng)生成方法),cacheManager(指定使用的緩存管理),cacheResolver(指定使用緩存的解析器)等,這些參數(shù)比較適合全局設(shè)置,這里就不多做介紹了。
@CachePut注解
@CachePut:當(dāng)需要更新緩存而不干擾方法的運(yùn)行時(shí) ,可以使用該注解。也就是說,始終執(zhí)行該方法,并將結(jié)果放入緩存,注解參數(shù)與@Cacheable相同。以下是一個(gè)簡單的例子:
@CachePut(cacheNames="book", key="#isbn")
public Book updateBook(ISBN isbn, BookDescriptor descriptor) 通常強(qiáng)烈建議不要對(duì)同一方法同時(shí)使用@CachePut和@Cacheable注解,因?yàn)樗鼈兙哂胁煌男袨?。可能?huì)產(chǎn)生不可思議的BUG哦。
@CacheEvict注解
@CacheEvict:刪除緩存的注解,這對(duì)刪除舊的數(shù)據(jù)和無用的數(shù)據(jù)是非常有用的。這里還多了一個(gè)參數(shù)(allEntries),設(shè)置allEntries=true時(shí),可以對(duì)整個(gè)條目進(jìn)行批量刪除。以下是個(gè)簡單的例子:
@CacheEvict(cacheNames="books")
public void loadBooks(InputStream batch)
//對(duì)cacheNames進(jìn)行批量刪除
@CacheEvict(cacheNames="books", allEntries=true)
public void loadBooks(InputStream batch) @Caching注解
@Caching:在使用緩存的時(shí)候,有可能會(huì)同時(shí)進(jìn)行更新和刪除,會(huì)出現(xiàn)同時(shí)使用多個(gè)注解的情況.而@Caching可以實(shí)現(xiàn)。以下是個(gè)簡單的例子:
@Caching(evict = { @CacheEvict("primary"), @CacheEvict(cacheNames="secondary", key="#p0") })
public Book importBooks(String deposit, Date date) @CacheConfig注解
@CacheConfig:緩存提供了許多的注解選項(xiàng),但是有一些公用的操作,我們可以使用@CacheConfig在類上進(jìn)行全局設(shè)置。以下是個(gè)簡單的例子:
@CacheConfig("books")
public class BookRepositoryImpl implements BookRepository {
@Cacheable
public Book findBook(ISBN isbn) {...}
} 可以共享緩存名稱,統(tǒng)一配置KeyGenerator,CacheManager,CacheResolver。
實(shí)例
在springboot中怎么使用redis來作為緩存.
為spring cache配置redis作為緩存
1.在pom.xml引入redis依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency> 2.springboot集成redis配置文件(在本地啟動(dòng)的redis),在springboot中使用redis,只要配置文件寫有redis配置,代碼就可以直接使用了。
spring:
redis:
database: 0 # Database index used by the connection factory.
url: redis://user:@127.0.0.1:6379 # Connection URL. Overrides host, port, and password. User is ignored. Example: redis://user:[email protected]:6379
host: 127.0.0.1 # Redis server host.
password: # Login password of the redis server.
port: 6379 # Redis server port.
ssl: false # Whether to enable SSL support.
timeout: 5000 # Connection timeout.
3.redis緩存配置類CacheConfig,這里對(duì)spring的緩存進(jìn)行了配置,包括KeyGenerator,CacheResolver,CacheErrorHandler,CacheManager,還有redis序列化方式。
@Configuration
public class CacheConfig extends CachingConfigurerSupport {
@Resource
private RedisConnectionFactory factory;
/**
* 自定義生成redis-key
*
* @return
*/
@Override
@Bean
public KeyGenerator keyGenerator() {
return (o, method, objects) -> {
StringBuilder sb = new StringBuilder();
sb.append(o.getClass().getName()).append(".");
sb.append(method.getName()).append(".");
for (Object obj : objects) {
sb.append(obj.toString());
}
System.out.println("keyGenerator=" + sb.toString());
return sb.toString();
};
}
@Bean
public RedisTemplate<Object, Object> redisTemplate() {
RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(factory);
GenericJackson2JsonRedisSerializer genericJackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer();
redisTemplate.setKeySerializer(genericJackson2JsonRedisSerializer);
redisTemplate.setValueSerializer(genericJackson2JsonRedisSerializer);
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setHashValueSerializer(genericJackson2JsonRedisSerializer);
return redisTemplate;
}
@Bean
@Override
public CacheResolver cacheResolver() {
return new SimpleCacheResolver(cacheManager());
}
@Bean
@Override
public CacheErrorHandler errorHandler() {
// 用于捕獲從Cache中進(jìn)行CRUD時(shí)的異常的回調(diào)處理器。
return new SimpleCacheErrorHandler();
}
@Bean
@Override
public CacheManager cacheManager() {
RedisCacheConfiguration cacheConfiguration =
defaultCacheConfig()
.disableCachingNullValues()
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
return RedisCacheManager.builder(factory).cacheDefaults(cacheConfiguration).build();
}
}
代碼使用
測試@Cacheable方法
@Test
public void findUserTest() {
for (int i = 0; i < 3; i++) {
System.out.println("第" + i + "次");
User user = userService.findUser();
System.out.println(user);
}
}
@Override
@Cacheable(value = {"valueName", "valueName2"}, key = "'keyName1'")
public User findUser() {
System.out.println("執(zhí)行方法...");
return new User("id1", "張三", "深圳", "1234567", 18);
} 執(zhí)行結(jié)果
只有一次輸出了'執(zhí)行方法...',后面直接從緩存獲取,不會(huì)再進(jìn)入方法。
第0次
執(zhí)行方法...
User{id='id1', name='張三', address='深圳', tel='1234567', age=18}
第1次
User{id='id1', name='張三', address='深圳', tel='1234567', age=18}
第2次
User{id='id1', name='張三', address='深圳', tel='1234567', age=18}

測試@CachePut方法:對(duì)緩存進(jìn)行了修改
@Test
public void updateUserTest() {
userService.updateUser();
User user = userService.findUser();
System.out.println(user);
}
@Override
@CachePut(value = "valueName", key = "'keyName1'")
public User updateUser() {
System.out.println("更新用戶...");
return new User("id1", "李四", "北京", "1234567", 18);
} 執(zhí)行結(jié)果
對(duì)緩存進(jìn)行了更新,獲取值的時(shí)候取了新的值
更新用戶...
User{id='id1', name='李四', address='北京', tel='1234567', age=18}

測試@CacheEvict方法:緩存被清空,再次findUser的時(shí)候又重新執(zhí)行了方法。
@Test
public void clearUserTest() {
userService.clearUser();
User user = userService.findUser();
System.out.println(user);
}
@Override
@CacheEvict(value = "valueName",allEntries = true)
public void clearUser() {
System.out.println("清除緩存...");
} 執(zhí)行結(jié)果
這里清除了緩存,為什么還是沒有執(zhí)行方法呢?因?yàn)檫@個(gè)方法我們定了兩個(gè)value值,清了一個(gè)還有一個(gè)
清除緩存...
User{id='id1', name='張三', address='深圳', tel='1234567', age=18}
source: cnblogs.com/wenjunwei/p/10779450.html

喜歡,在看
