为 Spring Boot 应用添加 Redis Caching

版权声明:欢迎关注我的个人公众号:超级码里奥。如果这对您有帮助,欢迎点赞和分享,转载请注明出处 https://blog.csdn.net/qq_28804275/article/details/89167838

中大型应用开发中,缓存的重要性不言而喻,早期常用的进程式类的缓存,像 EhCache 或者是 ConcurrentHashMap 这样的容器,发展到如今,更流行的是那些分布式的独立缓存服务,如:Redis、Memcached。

对于 Java 应用开发者来说,Spring 提供了完善的缓存抽象机制,结合 Spring Boot 的使用,可以做到非常轻松的完成缓存实现和切换。下面通过简单的示例,展示下如何快速为你的 Spring Boot 应用添加 Redis Caching。

  1. 加入依赖
<dependencies>
        <!-- 添加该依赖后,将自动使用 Redis 作为 Cache Provider -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
  1. 补充配置
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/test?useUnicode=true&zeroDateTimeBehavior=convertToNull&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8&tinyInt1isBit=false
    username: root
    password: root
  jpa:
    database-platform: org.hibernate.dialect.MySQL5InnoDBDialect
    hibernate:
      ddl-auto: create
    # 开启 SQL 输出,方便查看结果是否走了缓存
    show-sql: true
    open-in-view: false
  redis:
    host: localhost
  cache:
    # 非必须,但如果配置了需补充相应的依赖,否则会出错
    #type: redis
    redis:
      # 过期时间5秒,默认单位:毫秒,等同于设置成 5s、5S
      time-to-live: 5000
      key-prefix: cn.mariojd.cache.
      cache-null-values: false
  1. 添加实体,实现 Serializable 接口
@Data
@Entity
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class User implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    private String name;

}

定义 Repository 接口:

public interface UserRepository extends JpaRepository<User, Integer> {
}
  1. 编写 Service,进行缓存规则配置,核心注解有:@CacheConfig@Cacheable(缓存新增)、@CachePut(缓存更新)、@CacheEvict(缓存删除)
@Slf4j
@Service
@CacheConfig(cacheNames = "user")
public class UserService {

    @Resource
    private UserRepository userRepository;

    /**
     * Key name: key-prefix.classSimpleName.methodName?pn=xxx&ps=xxx&sort=xxx
     */
    @Cacheable(key = "#root.targetClass.simpleName+'.'+#root.methodName+'?pn='+#pageable.pageNumber+'&ps='+#pageable.pageSize+'&sort='+#pageable.sort.toString()")
    public Page<User> page(Pageable pageable) {
        return userRepository.findAll(pageable);
    }

    @Cacheable(key = "'user.'+#userId", unless = "#result == null")
    public Optional<User> get(int userId) {
        return userRepository.findById(userId);
    }

    @Transactional
    public User add(String name) {
        User user = User.builder().name(name).build();
        return userRepository.save(user);
    }

    @CachePut(key = "'user.'+#userId", unless = "#result == null")
    @Transactional
    public Optional<User> update(int userId, String name) {
        Optional<User> userOptional = userRepository.findById(userId);
        userOptional.ifPresent(user -> {
            user.setName(name);
            userRepository.save(user);
        });
        return userOptional;
    }

    @CacheEvict(key = "'user.'+#userId")
    @Transactional
    public void delete(int userId) {
        userRepository.findById(userId).ifPresent(user -> userRepository.delete(user));
    }

}
  1. 缓存测试,为启动类添加:@EnableCaching
@Slf4j
@EnableCaching
@SpringBootApplication
public class SpringBootCacheApplication implements ApplicationRunner {

    public static void main(String[] args) {
        new SpringApplicationBuilder()
                .sources(SpringBootCacheApplication.class)
                .bannerMode(Banner.Mode.OFF)
                .web(WebApplicationType.NONE)
                .run(args);
        log.info("\n");
    }

    @Resource
    private UserRepository userRepository;

    @PostConstruct
    public void init() {
        // 初始化数据
        for (int i = 0; i < 10; i++) {
            User user = User.builder().name("ZS" + i).build();
            userRepository.save(user);
        }
    }

    @Resource
    private UserService userService;

    @Resource
    private Environment environment;

    @Override
    public void run(ApplicationArguments args) throws InterruptedException {
        // 测试缓存,观察是否有SQL输出

        PageRequest pageable = PageRequest.of(0, 5);
        userService.page(pageable);
        for (int i = 0; i < 5; i++) {
            userService.page(pageable);
            log.info("Reading page cache...");
        }
        // 由于配置是5秒中后缓存失效,这里休眠后重新读取
        TimeUnit.MILLISECONDS.sleep(Integer.parseInt(environment.getProperty("spring.cache.redis.time-to-live", "5000")));
        log.warn("Page Cache expired : " + userService.page(pageable).getTotalElements());

        log.info("\n");

        // Test CRUD Cache![enter description here](http://image.mariojd.cn/happyjared/201949/20190409101855.png)
        User user = userService.add("李四");
        int userId = user.getId();
        userService.get(userId);
        log.info("Reading user cache..." + userService.get(userId));

        userService.update(userId, "王五");
        log.info("Reading new user cache..." + userService.get(userId));

        userService.delete(userId);
        log.warn("User Cache delete : " + userService.get(userId));
    }
    
}

从图中的红框部分输出可以看到,这些查询走了缓存,如果需要在 redis 中查看缓存内容,可以将配置中的 TTL 时间调大:

9709135-f60301cc0efc23bd.png

测试输出

扩展操作

Spring 允许开发者们通过自定义 KeyGenerator 来覆盖繁琐的 Key 定义(非必须),同时也允许我们配置自定义的 CacheManager,下面来看看如何编写 KeyGenerator:

9709135-757e61498521fcd2.png

@CacheConfig

@Slf4j
public class CustomKeyGenerator implements KeyGenerator {

    @Override
    public Object generate(Object target, Method method, Object... params) {
        // 类名.方法名.参数值
        String keySuffix = target.getClass().getSimpleName() + "." + method.getName() + "." + Arrays.toString(params);
        log.info("Cache key suffix : {}", keySuffix);
        return keySuffix;
    }

}

接着配置注册为 Bean:

@Configuration
public class CustomConfig {

    @Bean
    public CustomKeyGenerator customKeyGenerator() {
        return new CustomKeyGenerator();
    }

}

编写 Service 用于测试,具体的测试代码这里就不再贴出来了,有兴趣的可以自行尝试。

@Slf4j
@Service
@CacheConfig(cacheNames = "user")
public class UserSupportService {

    @Resource
    private UserRepository userRepository;

    /**
     * 使用了自定义的KeyGenerator
     * 缓存生效需满足:存在不为空的入参i、且返回值非空
     */
    @Cacheable(keyGenerator = "customKeyGenerator", condition = "#i!=null", unless = "#result.isEmpty()")
    public List<User> list(Integer i) {
        return userRepository.findAll();
    }

}

参考阅读

Spring-Boot-Caching

示例源码
欢迎关注我的个人公众号:超级码里奥
如果这对您有帮助,欢迎点赞和分享,转载请注明出处

猜你喜欢

转载自blog.csdn.net/qq_28804275/article/details/89167838
今日推荐