欢迎访问移动开发之家(rcyd.net),关注移动开发教程。移动开发之家  移动开发问答|  每日更新
页面位置 : > > > 内容正文

SpringBoot3.0集成Redis缓存的实现示例,

来源: 开发者 投稿于  被查看 49667 次 评论:77

SpringBoot3.0集成Redis缓存的实现示例,


目录
  • 一、什么是redis缓存
  • 二、SpringBoot3 如何集成 Redis
  • 三、spring-boot-starter-cache 结合 Redis 使用
    • 1、什么是 spring-boot-starter-cache
    • 2、Redis 集成步骤
    • 3、使用示例
  • 参考

    一、什么是redis缓存

    Redis缓存是一个开源的使用ANSIC语言编写、支持网络、可基于内存亦可持久化的日志型、Key-Value数据库,并提供多种语言的API。它主要用于作为数据库、缓存和消息中间件,以快速读写和丰富的数据结构支持而著称。

    在应用程序和数据库之间,Redis缓存作为一个中间层起着关键作用。通过将常用的数据存储在Redis内存中,可以快速读取,从而避免了从数据库进行复杂的查询操作,减轻了数据库服务器的压力,并提高了应用程序的性能和响应速度。

    此外,为了优化热门查询的性能,可以确定希望缓存的查询结果,特别是最常用和最耗时的查询。这样可以进一步提高应用程序的性能和吞吐量。

    spring-boot-starter-data-redis默认的Redis客户端是Lettuce。这是因为Lettuce是一个线程安全的、基于Netty通信的Redis客户端,相比之下,Jedis在多线程环境下存在线程安全问题,因此需要增加连接池来解决线程安全的问题,同时可以限制redis客户端的数量。

    而Lettuce在多线程环境下不存在线程安全问题,一个连接实例就可以满足多线程环境下的并发访问,当然实例不够的情况下也可以按需增加实例,保证伸缩性。因此,Spring Boot在后续版本中选择了Lettuce作为默认的Redis客户端。

    二、SpringBoot3 如何集成 Redis

    1)添加依赖

    在pom.xml文件中添加Spring Boot Starter Data Redis依赖:

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

    2)配置Redis连接

    在application.properties或application.yml文件中配置Redis连接信息:

    spring.data.redis.host=127.0.0.1
    spring.data.redis.port=6379
    spring.data.redis.database=0
    spring.data.redis.password=
    

    3)配置 RedisTemplate Bean

    @Configuration  
    public class RedisConfig {  
    	@Bean
    	public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
    		RedisTemplate<Object, Object> template = new RedisTemplate<>();
    		template.setConnectionFactory(connectionFactory);
    		// 使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式)
    		Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<>(Object.class);
    		template.setValueSerializer(serializer);
    		template.setKeySerializer(new StringRedisSerializer());
    		template.setHashKeySerializer(new StringRedisSerializer());
    		template.setHashValueSerializer(serializer);
    		return template;
    	}
    }
    

    4)使用示例

    import org.junit.jupiter.api.Test;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.data.redis.core.RedisTemplate;
    
    @SpringBootTest
    public class RedisTemplateTest {
        @Autowired
        private RedisTemplate<String, Object> redisTemplate;
    
        @Test
        void test() {
            redisTemplate.opsForValue().set("key_name", "my name is Jacky");
            System.out.println("缓存设置成功");
            String value = (String) redisTemplate.opsForValue().get("key_name");
            System.out.println(value);
        }
    }
    

    三、spring-boot-starter-cache 结合 Redis 使用

    1、什么是 spring-boot-starter-cache

    Spring Boot Starter Cache 是 Spring Boot 体系内提供使用 Spring Cache 的 Starter 包。它可以为你的 Spring Boot 应用提供缓存支持,简化和自动化缓存的配置和识别。通过使用 Spring Cache 的抽象层,开发者可以轻松地使用各种缓存解决方案。

    Spring Boot Starter Cache 集成了各种主流缓存实现(ConcurrentMapredisehcacheCaffeine等)

    Spring Boot Starter Cache 默认使用ConcurrentMap作为缓存;如果工程中引入了redis配置,则会使用redis作为缓存

    Spring Boot Starter Cache 通过CacheManager判断具体使用哪个缓存,每个缓存都有一个具体的CacheManager(比如:EhCacheCacheManagerRedisCacheManagerCaffeineCacheManager),如果没有配置任何的CacheManager,则会使用ConcurrentMap作为缓存

    常用注解说明:

    名称说明
    @EnableCaching开启基于注解的缓存
    @CacheConfig统一配置本类的缓存注解的属性
    @Cacheable常用于查询方法,能够根据方法的请求参数对其进行缓存
    @CachePut常用于更新/保存方法,会将方法返回值放入缓存
    @CacheEvict清空缓存

    2、Redis 集成步骤

    下面是如何在 Spring Boot 应用中使用 spring-boot-starter-cache 与 Redis 进行集成的步骤:

    • 添加依赖:
      在你的 pom.xml 文件中添加 spring-boot-starter-cache 和 spring-boot-starter-data-redis 的依赖。
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-cache</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
    
    • 配置 Redis:
      在 application.properties 或 application.yml 文件中配置 Redis 连接信息。

    • 启用缓存支持:
      在你的 Spring Boot 主类或配置类上添加 @EnableCaching 注解以启用缓存支持。

    • 定义缓存配置:
      你可以创建一个配置类并实现 CacheManagerCustomizer 接口来自定义缓存配置。或者,你可以使用 @EnableCaching 注解并使用属性来定义缓存配置。

      CacheManagerCustomizer是一个Spring框架的接口,它允许用户自定义扩展CacheManager。

      当需要对某个CacheManager实现进行一些自定义时,可以实现CacheManagerCustomizer接口,指定泛型为需要进行自定义的CacheManager实现类,然后把它定义为一个Spring bean。通过实现这个接口,你可以对Spring的CacheManager进行自定义扩展,例如配置缓存策略、设置缓存过期时间等。

      这个接口的使用可以帮助开发者更好地控制和优化缓存的行为,提高应用程序的性能和响应速度。在实现自定义扩展时,可以使用Spring的注解或XML配置来定义自定义逻辑,并根据需要选择是否将自定义的逻辑应用到所有CacheManager实现上,或者只应用到特定的CacheManager实现上。

    @Configuration  
    public class CacheConfig {  
        @Bean  
        public CacheManagerCustomizer cacheManagerCustomizer() {  
            return (cacheManager) -> {  
                SimpleKeyGenerator keyGenerator = new SimpleKeyGenerator();  
                keyGenerator.setSalt("some_salt"); //设置盐值,增强安全性  
                cacheManager.getCache("my_cache").setKeyGenerator(keyGenerator); //设置key生成策略  
            };  
        }  
    }
    
    • 使用缓存注解:
      在你的服务类中的方法上使用 Spring 的缓存注解,例如 @Cacheable@CacheEvict@CachePut 等。这样,当这些方法被调用时,它们将与 Redis 缓存进行交互。
    • 自定义序列化:
      如果你需要自定义序列化,你可以创建一个配置类并实现 RedisSerializer 接口。然后,你可以在 Redis 的相关配置中指定这个序列化器。
    private Jackson2JsonRedisSerializer<Object> jacksonSerializer() {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setVisibility(PropertyAccessor.ALL, Visibility.ANY);
        objectMapper.activateDefaultTyping(objectMapper.getPolymorphicTypeValidator(), ObjectMapper.DefaultTyping.NON_FINAL);
        return new Jackson2JsonRedisSerializer<>(objectMapper,Object.class);
    }
    

    3、使用示例

    1、创建测试Service

    @Service
    public class MyService {
        @Cacheable(value = "my_cache") //将方法结果缓存到"my_cache"中,key为方法参数的哈希值
        public String getSomeData(String id) throws InterruptedException {
            // 模拟一个耗时操作,比如从数据库中获取数据
            Thread.sleep(1000); //休眠1秒,模拟耗时操作
            return "data for " + id;
        }
    }
    

    2、创建测试类

    import lombok.extern.slf4j.Slf4j;
    import org.junit.jupiter.api.Test;
    import org.shi9.module.system.service.MyService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.util.StopWatch;
    
    @Slf4j
    @SpringBootTest
    public class MyServiceTest {
        @Autowired
        private MyService myService;
    
        @Test
        public void getData() throws Exception {
            StopWatch stopWatch = new StopWatch("getData");
            stopWatch.start("1");
            System.out.println(myService.getSomeData("k"));
            stopWatch.stop();
            stopWatch.start("2");
            System.out.println(myService.getSomeData("k"));
            stopWatch.stop();
            stopWatch.start("3");
            System.out.println(myService.getSomeData("k"));
            stopWatch.stop();
            System.out.println(stopWatch.prettyPrint());
        }
    
    }
    

    执行结果如下:

    data for k
    data for k
    data for k
    StopWatch 'getData': 1.3141034 seconds
    ----------------------------------------
    Seconds       %       Task name
    ----------------------------------------
    1.3104986     100%    1
    0.0029345     00%     2
    0.0006703     00%     3

    可以看见,只有第一次执行耗时,后面两次直接从缓存读取,几乎没有耗时

    参考

    • spring-boot-starter-cache
    • spring-boot-starter-redis

    到此这篇关于SpringBoot3.0集成Redis缓存的实现示例的文章就介绍到这了,更多相关SpringBoot集成Redis缓存内容请搜索3672js教程以前的文章或继续浏览下面的相关文章希望大家以后多多支持3672js教程! 

    您可能感兴趣的文章:
    • SpringBoot整合Redis实现token缓存
    • SpringBoot结合Redis实现缓存管理功能
    • SpringBoot整合redis使用缓存注解详解
    • SpringBoot+MyBatis+Redis实现分布式缓存
    • springboot使用redis注解做缓存的基本操作方式
    • SpringBoot中Redis的缓存更新策略详解
    • springboot整合ehcache和redis实现多级缓存实战案例
    • SpringBoot结合Redis实现缓存
    • SpringBoot使用Redis实现分布式缓存
    • SpringBoot中的Redis 缓存问题及操作方法

    用户评论