前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >SpringBoot通过CacheManager集成redis做缓存

SpringBoot通过CacheManager集成redis做缓存

作者头像
taixingyiji
发布2022-07-25 15:35:07
1.2K0
发布2022-07-25 15:35:07
举报
文章被收录于专栏:taixingyiji的博客笔记

# SpringBoot通过CacheManager集成redis做缓存

SpringBoot如何通过 CacheManager 集成 redis做缓存

SpringBoot在annotation的层面实现了数据缓存的功能,基于Spring的AOP技术。所有的缓存配置只是在annotation层面配置,像声明式事务一样。

Spring定义了CacheManager 和Cache接口统一不同的缓存技术。其中CacheManager 是Spring提供的各种缓存技术的抽象接口。而Cache接口包含缓存的各种操作。

# 1. 添加依赖

引入springboot-cachespring-redis

代码语言:javascript
复制
    <!-- 缓存 -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-cache</artifactId>
    </dependency>
    <!-- redis -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>

# 2. application配置

此处我选择使用 .yml 文件配置

代码语言:javascript
复制
spring:
  # 缓存设置
  cache:
    # redis缓存
    type: redis
    redis:
    	# 缓存超时默认时间,此处设置为一天
      time-to-live: 1d
      # 是否启用缓存key统一前缀,默认为true
      use-key-prefix: true
      # 是否保存null值,默认为true
      cache-null-values: true
      # 设置缓存key前缀
      key-prefix: cache.
  redis:
    database: 0
    host: 192.168.4.119
    port: 6379
    password:
    lettuce:
      pool:
        # 连接池中的最大空闲连接 默认8
        max-idle: 8
        # 连接池中的最小空闲连接 默认0
        min-idle: 0
        # 连接池最大连接数 默认8 ,负数表示没有限制
        max-active: 8
        # 连接池最大阻塞等待时间(使用负值表示没有限制) 默认-1
        max-wait: -1
    timeout: 30000

# 3.入口类配置

加入注解 @EnableCaching

代码语言:javascript
复制
@SpringBootApplication
@EnableCaching
public class DemoApplication {
}

# 4.redis配置类

代码语言:javascript
复制
@Configuration
public class RedisConfig {

    /**
     * springboot2.x 使用LettuceConnectionFactory 代替 RedisConnectionFactory
     * application.yml配置基本信息后,springboot2.x  RedisAutoConfiguration能够自动装配
     * LettuceConnectionFactory 和 RedisConnectionFactory 及其 RedisTemplate
     * @param redisConnectionFactory
     * @return
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        return redisTemplate;
    }
}

# 5.使用Cache

注入SpringBoot自动配置的bean,org.springframework.cache.CacheManager。 一个简单的测试类:

代码语言:javascript
复制
package com.bbf.frame.test;

import com.bbf.frame.Application;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;

import javax.annotation.Resource;

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@SpringBootTest(classes = Application.class, webEnvironment = SpringBootTest.WebEnvironment.MOCK)
public class TestCache {
  @Resource
  private CacheManager cacheManager;

  @Test
  public void cacheTest() {
    // 显示所有的Cache空间
    System.out.println(StringUtils.join(cacheManager.getCacheNames(), ","));
    Cache cache = cacheManager.getCache("userCache");
    cache.put("key", "123");
    System.out.println("缓存成功");
    String res = cache.get("key", String.class);
    System.out.println(res);
  }
}
# CacheManager转换
代码语言:javascript
复制
    // 获取EhCache的管理器
    org.springframework.cache.ehcache.EhCacheCacheManager cacheCacheManager = (EhCacheCacheManager) cacheManager;
    net.sf.ehcache.CacheManager ehCacheManager = cacheCacheManager.getCacheManager();
    net.sf.ehcache.Cache ehCache = ehCacheManager.getCache("userCache");

# 结束语

至于如何使用CacheManger的注解这里不再赘述,网上有大把的资料供大家参考了。

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020-12-31,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • # SpringBoot通过CacheManager集成redis做缓存
    • # 1. 添加依赖
      • # 2. application配置
        • # 3.入口类配置
          • # 4.redis配置类
            • # 5.使用Cache
              • # 结束语
              相关产品与服务
              云数据库 Redis
              腾讯云数据库 Redis(TencentDB for Redis)是腾讯云打造的兼容 Redis 协议的缓存和存储服务。丰富的数据结构能帮助您完成不同类型的业务场景开发。支持主从热备,提供自动容灾切换、数据备份、故障迁移、实例监控、在线扩容、数据回档等全套的数据库服务。
              领券
              问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档