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

 更新时间:2024年03月03日 15:41:45   作者:顽石九变  
缓存就是一个存储器,常用 Redis作为缓存数据库,本文主要介绍了SpringBoot3.0集成Redis缓存的实现示例,具有一定的参考价值,感兴趣的可以了解一下
(福利推荐:【腾讯云】服务器最新限时优惠活动,云服务器1核2G仅99元/年、2核4G仅768元/3年,立即抢购>>>:9i0i.cn/qcloud

(福利推荐:你还在原价购买阿里云服务器?现在阿里云0.8折限时抢购活动来啦!4核8G企业云服务器仅2998元/3年,立即抢购>>>:9i0i.cn/aliyun

一、什么是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

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

参考

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

相关文章

  • SwiftUI?List在MacOS中的性能优化示例

    SwiftUI?List在MacOS中的性能优化示例

    这篇文章主要为大家介绍了SwiftUI?List在MacOS中的性能优化示例,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-09-09
  • swift 可选型的使用详解

    swift 可选型的使用详解

    可选性是Swift提供的一个特殊类型,它为我们编写程序提供便利的条件。这篇文章主要介绍了swift 可选型的使用详解,非常不错具有参考借鉴价值,需要的朋友可以参考下
    2016-10-10
  • Swift编程之枚举类型详解

    Swift编程之枚举类型详解

    这篇文章主要介绍了Swift编程之枚举类型,讲解了枚举语法、匹配枚举值与switch语句、关联值、原始值等内容,Swift中枚举类型是最重要的类型,感兴趣的小伙伴们可以参考一下
    2016-02-02
  • LeetCode?刷题?Swift?两个数组的交集

    LeetCode?刷题?Swift?两个数组的交集

    这篇文章主要为大家介绍了LeetCode?刷题?Swift?两个数组的交集示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-09-09
  • Swift中使用正则表达式的一些方法

    Swift中使用正则表达式的一些方法

    这篇文章主要介绍了Swift中使用正则表达式的一些方法,Swift语言对正则表达式的支持也在不断改进中,需要的朋友可以参考下
    2015-07-07
  • Swift 中闭包的简单使用

    Swift 中闭包的简单使用

    这篇文章主要介绍了Swift 中闭包的简单使用的相关资料,需要的朋友可以参考下
    2016-10-10
  • Swift4.1转场动画实现侧滑抽屉效果

    Swift4.1转场动画实现侧滑抽屉效果

    这篇文章主要为大家详细介绍了Swift4.1转场动画实现侧滑抽屉效果,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2019-06-06
  • 为什么switch里的case没有break不行

    为什么switch里的case没有break不行

    很多朋友纠结为什么为什么switch里的case没有break不行呢?break这么重要么,今天小编就给大家普及下这方便的知识,感兴趣的朋友一起看看吧
    2021-06-06
  • 深入理解Swift中单例模式的替换及Swift 3.0单例模式的实现

    深入理解Swift中单例模式的替换及Swift 3.0单例模式的实现

    这篇文章主要给大家介绍了关于Swift中单例模式替换的相关资料,然后又跟大家分享了关于Swift3.0 单例模式实现的几种方法-Dispatch_Once的内容,文中通过示例代码介绍的非常详细,需要的朋友可以参考借鉴,下面来一起看看吧。
    2017-11-11
  • Swift 编程语言入门教程

    Swift 编程语言入门教程

    今天在网上看到一篇非常好的Swift 编程语言入门教程,分享给大家
    2014-08-08

最新评论

?


http://www.vxiaotou.com