【Java进阶营】SpringBoot技术专题-整合SpringCache和Redis

x33g5p2x  于2022-04-26 转载在 Java  
字(8.9k)|赞(0)|评价(0)|浏览(721)

Spring基于注解的缓存

对于缓存声明,spring的缓存提供了一组java注解:

@Cacheable:触发缓存写入。

@CacheEvict:触发缓存清除。

@CachePut:更新缓存(不会影响到方法的运行)。

@Caching:重新组合要应用于方法的多个缓存操作。

@CacheConfig:设置类级别上共享的一些常见缓存设置。

@Cacheable注解

顾名思义,@Cacheable可以用来进行缓存的写入,将结果存储在缓存中,以便于在后续调用的时候可以直接返回缓存中的值,而不必再执行实际的方法。

  1. 最简单的使用方式,注解名称 = 缓存名称,使用例子如下:

@Cacheable(“books”)

public Book findBook(ISBN isbn) {…}

一个方法可以对应两个缓存名称,如下:

@Cacheable({“books”, “isbns”})

public Book findBook(ISBN isbn) {…}

  1. @Cacheable的缓存名称是可以配置动态参数的,比如选择传入的参数,如下: (以下示例是使用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)

  1. @Cacheable还可以设置根据条件判断是否需要缓存

condition:取决于给定的参数是否满足条件

unless:取决于返回值是否满足条件

以下是一个简单的例子:

@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还可以设置:keyGenerator(指定key自动生成方法),cacheManager(指定使用的缓存管

理),cacheResolver(指****定使用缓存的解析器)等,这些参数比较适合全局设置,这里就不多做介绍了。

@CachePut注解

  1. @CachePut:当需要更新缓存而不干扰方法的运行时 ,可以使用该注解。也就是说,始终执行该方法,并将结果放入缓

存,注解参数与@Cacheable相同。 以下是一个简单的例子:

@CachePut (cacheNames=“book”, key=“#isbn”)

public Book updateBook(ISBN isbn, BookDescriptor descriptor)

  1. **通常强烈建议不要对同一方法同时使用@CachePut@Cacheable注解,因为它们具有不同的行为。可能会产生不可**

思议的BUG哦。

@CacheEvict注解

  1. @CacheEvict:删除缓存的注解,这对删除旧的数据和无用的数据是非常有用的。这里还多了一个参数(allEntries),设置

allEntries=true时,可以对整个条目进行批量删除。 以下是个简单的例子:

@CacheEvict(cacheNames=“books”)

public void loadBooks(InputStream batch)

//对cacheNames进行批量删除@CacheEvict(cacheNames=“books”, allEntries=true)

public void loadBooks(InputStream batch)

@Caching注解

  1. @Caching:在使用缓存的时候,有可能会同时进行更新和删除,会出现同时使用多个注解的情况.而@Caching可以实

现。以下是个简单的例子:

@Caching(evict = { @CacheEvict(“primary”), @CacheEvict(cacheNames=“secondary”, key=“#p0”) })

public Book importBooks(String deposit, Date date)

@CacheConfig注解

  1. @CacheConfig:缓存提供了许多的注解选项,但是有一些公用的操作,我们可以使用@CacheConfig在类上进行全局设置。在此我向大家推荐一个架构学习交流圈。交流学习指导伪鑫:1253431195(里面有大量的面试题及答案)里面会分享一些资深架构师录制的视频录像:有SpringMyBatisNetty源码分析,高并发、高性能、分布式、微服务架构的原理,JVM性能优化、分布式架构等这些成为架构师必备的知识体系。还能领取免费的学习资源,目前受益良多
  2. 以下是个简单的例子:

@CacheConfig(“books”)

public class BookRepositoryImpl implements BookRepository {

@Cacheable

public Book findBook(ISBN isbn) {…}

}

  1. 可以共享缓存名称,统一配置KeyGenerator,CacheManager,CacheResolver

实例

来看看我们在springboot中怎么使用redis来作为缓存吧.

为spring cache配置redis作为缓存

1.在pom.xml引入redis依赖

  1. <groupId>org.springframework.boot</groupId>
  2. <artifactId>spring-boot-starter-data-redis</artifactId>

2. springboot集成redis配置文件(在本地启动的redis)

  1. springboot中使用redis,只要配置文件写有redis配置,代码就可以直接使用了。

spring:

redis:

  1. database: 0 # Database index used by the connection factory.
  2. url: redis://user:@127.0.0.1:6379

Connection URL. Overrides host, port, and password. User is ignored. Example: redis://user:password@example.com:6379host: 127.0.0.1 # Redis server host.

  1. password: # Login password of the redis server.
  2. port: 6379 # Redis server port.
  3. ssl: false # Whether to enable SSL support.
  4. timeout: 5000 # Connection timeout.

3.redis缓存配置类CacheConfig

这里对spring的缓存进行了配置,包括
KeyGenerator,CacheResolver,CacheErrorHandler,CacheManager,还有redis序列化方式。

/**

  • @author wwj

*/

  1. @Configuration
  2. public class CacheConfig extends CachingConfigurerSupport {
  3. @Resource
  4. private RedisConnectionFactory factory;
  5. /**
  6. * 自定义生成redis-key
  7. *
  8. * @return
  9. */
  10. @Override
  11. @Bean
  12. public KeyGenerator keyGenerator() {
  13. return(o, method, objects) -> {
  14. StringBuilder sb =new StringBuilder();
  15. sb.append(o.getClass().getName()).append(".");
  16. sb.append(method.getName()).append(".");
  17. for (Object obj : objects) {
  18. sb.append(obj.toString());
  19. }
  20. System.out.println("keyGenerator=" + sb.toString());
  21. return sb.toString();
  22. };
  23. }
  24. @Bean
  25. publicRedisTemplate redisTemplate() {
  26. RedisTemplate redisTemplate =newRedisTemplate<>();
  27. redisTemplate.setConnectionFactory(factory);
  28. GenericJackson2JsonRedisSerializer genericJackson2JsonRedisSerializer =new GenericJackson2JsonRedisSerializer();
  29. redisTemplate.setKeySerializer(genericJackson2JsonRedisSerializer);
  30. redisTemplate.setValueSerializer(genericJackson2JsonRedisSerializer);
  31. redisTemplate.setHashKeySerializer(new StringRedisSerializer());
  32. redisTemplate.setHashValueSerializer(genericJackson2JsonRedisSerializer);
  33. return redisTemplate;
  34. }
  35. @Bean
  36. @Override
  37. public CacheResolver cacheResolver() {
  38. return new SimpleCacheResolver(cacheManager());
  39. }
  40. @Bean
  41. @Override
  42. public CacheErrorHandler errorHandler() {
  43. // 用于捕获从Cache中进行CRUD时的异常的回调处理器。
  44. return new SimpleCacheErrorHandler();
  45. }
  46. @Bean
  47. @Override
  48. public CacheManager cacheManager() {
  49. RedisCacheConfiguration cacheConfiguration = defaultCacheConfig()
  50. .disableCachingNullValues()
  51. .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
  52. return RedisCacheManager.builder(factory).cacheDefaults(cacheConfiguration).build();
  53. }

}

代码使用

测试@Cacheable方法

  1. @Test
  2. publicvoid findUserTest() {
  3. for(inti = 0; i < 3; i++) {
  4. System.out.println("第" + i + "次");
  5. User user = userService.findUser();
  6. System.out.println(user);
  7. }
  8. }
  9. @Override
  10. @Cacheable(value = {"valueName", "valueName2"}, key = "'keyName1'")
  11. public User findUser() {
  12. System.out.println("执行方法...");
  13. returnnewUser("id1", "张三", "深圳", "1234567", 18);
  14. }

执行结果

只有一次输出了’执行方法…',后面直接从缓存获取,不会再进入方法。

第0次

执行方法…

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方法:对缓存进行了修改

  1. @Test
  2. publicvoid updateUserTest() {
  3. userService.updateUser();
  4. User user = userService.findUser();
  5. System.out.println(user);
  6. }
  7. @Override
  8. @CachePut(value = "valueName", key = "'keyName1'")
  9. public User updateUser() {
  10. System.out.println("更新用户...");
  11. returnnewUser("id1", "李四", "北京", "1234567", 18);
  12. }

执行结果

对缓存进行了更新,获取值的时候取了新的值

更新用户…

User{id=‘id1’, name=‘李四’, address=‘北京’, tel=‘1234567’, age=18}

测试@CacheEvict方法:缓存被清空,再次findUser的时候又重新执行了方法。

  1. @Test
  2. publicvoid clearUserTest() {
  3. userService.clearUser();
  4. User user = userService.findUser();
  5. System.out.println(user);
  6. }
  7. @Override
  8. @CacheEvict(value = "valueName",allEntries =true)
  9. publicvoid clearUser() {
  10. System.out.println("清除缓存...");
  11. }

执行结果

这里清除了缓存,为什么还是没有执行方法呢?因为这个方法我们定了两个value值,清了一个还有一个

清除缓存…

User{id=‘id1’, name=‘张三’, address=‘深圳’, tel=‘1234567’, age=18}

最后贴一下代码吧

User.java

package com.wwj.springboot.model;import java.io.Serializable;/** * @author wwj

*/publicclassUserimplements Serializable {

  1. public User() {
  2. }
  3. private String id;
  4. private String name;
  5. private String address;
  6. private String tel;
  7. private Integer age;
  8. //省略get,set,tostring}

CacheTest.java

package com.wwj.springboot.cache;import com.wwj.springboot.model.User;import com.wwj.springboot.service.UserService;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.cache.annotation.EnableCaching;import org.springframework.test.context.junit4.SpringRunner;import javax.annotation.Resource;/** * @author wwj

*/@RunWith(SpringRunner.class)

@SpringBootTest

@EnableCachingpublicclass CacheTest {

  1. @Resource
  2. private UserService userService;
  3. @Test
  4. publicvoid findUserTest() {
  5. for(inti = 0; i < 3; i++) {
  6. System.out.println("第" + i + "次");
  7. User user = userService.findUser();
  8. System.out.println(user);
  9. }
  10. }
  11. @Test
  12. publicvoid updateUserTest() {
  13. userService.updateUser();
  14. User user = userService.findUser();
  15. System.out.println(user);
  16. }
  17. @Test
  18. publicvoid clearUserTest() {
  19. userService.clearUser();
  20. User user = userService.findUser();
  21. System.out.println(user);
  22. }

}

UserService.java

package com.wwj.springboot.service;import com.wwj.springboot.model.User;import java.util.List;/** * @author wwj

*/publicinterface UserService {

  1. /** * 获取用户
  2. * @return user
  3. */ User findUser();
  4. /** * 更新用户信息
  5. * @return user
  6. */ User updateUser();
  7. /** * 清除缓存的用户信息
  8. */void clearUser();

}

UserServiceImpl.java

package com.wwj.springboot.service.impl;import com.wwj.springboot.model.User;import com.wwj.springboot.service.UserService;import org.springframework.cache.annotation.CacheConfig;import org.springframework.cache.annotation.CacheEvict;import org.springframework.cache.annotation.CachePut;import org.springframework.cache.annotation.Cacheable;import org.springframework.stereotype.Service;

/**

  • @author wwj

*/

@Service

@CacheConfig(cacheNames = “CacheConfigName”)publicclassUserServiceImplimplements UserService {

  1. @Override
  2. @Cacheable(value = {"valueName", "valueName2"}, key = "'keyName1'")
  3. public User findUser() {
  4. System.out.println("执行方法...");
  5. return new User("id1", "张三", "深圳", "1234567", 18);
  6. }
  7. @Override
  8. @CachePut(value = "valueName", key = "'keyName1'")
  9. public User updateUser() {
  10. System.out.println("更新用户...");
  11. returnnewUser("id1", "李四", "北京", "1234567", 18);
  12. }
  13. @Override
  14. @CacheEvict(value = "valueName",allEntries =true)
  15. publicvoid clearUser() {
  16. System.out.println("清除缓存...");
  17. }

}

相关文章