SpringBoot3.0集成Redis缓存的实现示例
<div id="navCategory"><h5 class="catalogue">目录</h5><ul class="first_class_ul"><li>一、什么是redis缓存</li><li>二、SpringBoot3 如何集成 Redis</li><li>三、spring-boot-starter-cache 结合 Redis 使用</li><ul class="second_class_ul"><li>1、什么是 spring-boot-starter-cache</li><li>2、Redis 集成步骤</li><li>3、使用示例</li></ul><li>参考</li><ul class="second_class_ul"></ul></ul></div><p class="maodian"></p><h2>一、什么是redis缓存</h2><p>Redis缓存是一个开源的使用ANSIC语言编写、支持网络、可基于内存亦可持久化的日志型、Key-Value数据库,并提供多种语言的API。它主要用于作为数据库、缓存和消息中间件,以快速读写和丰富的数据结构支持而著称。</p>
<p>在应用程序和数据库之间,Redis缓存作为一个中间层起着关键作用。通过将常用的数据存储在Redis内存中,可以快速读取,从而避免了从数据库进行复杂的查询操作,减轻了数据库服务器的压力,并提高了应用程序的性能和响应速度。</p>
<p>此外,为了优化热门查询的性能,可以确定希望缓存的查询结果,特别是最常用和最耗时的查询。这样可以进一步提高应用程序的性能和吞吐量。</p>
<p>spring-boot-starter-data-redis默认的Redis客户端是Lettuce。这是因为Lettuce是一个线程安全的、基于Netty通信的Redis客户端,相比之下,Jedis在多线程环境下存在线程安全问题,因此需要增加连接池来解决线程安全的问题,同时可以限制redis客户端的数量。</p>
<p>而Lettuce在多线程环境下不存在线程安全问题,一个连接实例就可以满足多线程环境下的并发访问,当然实例不够的情况下也可以按需增加实例,保证伸缩性。因此,Spring Boot在后续版本中选择了Lettuce作为默认的Redis客户端。</p>
<p class="maodian"></p><h2>二、SpringBoot3 如何集成 Redis</h2>
<p><strong>1)添加依赖</strong></p>
<p>在pom.xml文件中添加Spring Boot Starter Data Redis依赖:</p>
<div class="jb51code"><pre class="brush:xml;"><dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
</pre></div>
<p><strong>2)配置Redis连接</strong></p>
<p>在application.properties或application.yml文件中配置Redis连接信息:</p>
<div class="jb51code"><pre class="brush:yaml;">spring.data.redis.host=127.0.0.1
spring.data.redis.port=6379
spring.data.redis.database=0
spring.data.redis.password=
</pre></div>
<p><strong>3)配置</strong> <code>RedisTemplate</code> <strong>Bean</strong></p>
<div class="jb51code"><pre class="brush:java;">@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;
}
}
</pre></div>
<p><strong>4)使用示例</strong></p>
<div class="jb51code"><pre class="brush:java;">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);
}
}
</pre></div>
<p class="maodian"></p><h2>三、spring-boot-starter-cache 结合 Redis 使用</h2>
<p class="maodian"></p><h3>1、什么是 spring-boot-starter-cache</h3>
<p>Spring Boot Starter Cache 是 Spring Boot 体系内提供使用 Spring Cache 的 Starter 包。它可以为你的 Spring Boot 应用提供缓存支持,简化和自动化缓存的配置和识别。通过使用 Spring Cache 的抽象层,开发者可以轻松地使用各种缓存解决方案。</p>
<p>Spring Boot Starter Cache 集成了各种主流缓存实现(<code>ConcurrentMap</code>、<code>redis</code>、<code>ehcache</code>、<code>Caffeine</code>等)</p>
<p>Spring Boot Starter Cache 默认使用<code>ConcurrentMap</code>作为缓存;如果工程中引入了<code>redis</code>配置,则会使用<code>redis</code>作为缓存</p>
<p>Spring Boot Starter Cache 通过<code>CacheManager</code>判断具体使用哪个缓存,每个缓存都有一个具体的<code>CacheManager</code>(比如:<code>EhCacheCacheManager</code>,<code>RedisCacheManager</code>,<code>CaffeineCacheManager</code>),如果没有配置任何的<code>CacheManager</code>,则会使用<code>ConcurrentMap</code>作为缓存</p>
<p><strong>常用注解说明:</strong></p>
<table><tbody><tr><th>名称</th><th>说明</th></tr><tr><td>@EnableCaching</td><td>开启基于注解的缓存</td></tr><tr><td>@CacheConfig</td><td>统一配置本类的缓存注解的属性</td></tr><tr><td>@Cacheable</td><td>常用于查询方法,能够根据方法的请求参数对其进行缓存</td></tr><tr><td>@CachePut</td><td>常用于更新/保存方法,会将方法返回值放入缓存</td></tr><tr><td>@CacheEvict</td><td>清空缓存</td></tr></tbody></table>
<p class="maodian"></p><h3>2、Redis 集成步骤</h3>
<p>下面是如何在 Spring Boot 应用中使用 <code>spring-boot-starter-cache</code> 与 Redis 进行集成的步骤:</p>
<ul><li><strong>添加依赖</strong>:<br />在你的 <code>pom.xml</code> 文件中添加 <code>spring-boot-starter-cache</code> 和 <code>spring-boot-starter-data-redis</code> 的依赖。</li></ul>
<div class="jb51code"><pre class="brush:xml;"><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>
</pre></div>
<ul><li><p><strong>配置 Redis</strong>:<br />在 <code>application.properties</code> 或 <code>application.yml</code> 文件中配置 Redis 连接信息。</p></li><li><p><strong>启用缓存支持</strong>:<br />在你的 Spring Boot 主类或配置类上添加 <code>@EnableCaching</code> 注解以启用缓存支持。</p></li><li><p><strong>定义缓存配置</strong>:<br />你可以创建一个配置类并实现 <code>CacheManagerCustomizer</code> 接口来自定义缓存配置。或者,你可以使用 <code>@EnableCaching</code> 注解并使用属性来定义缓存配置。</p>
<p><code>CacheManagerCustomizer</code>是一个Spring框架的接口,它允许用户自定义扩展CacheManager。</p>
<p>当需要对某个CacheManager实现进行一些自定义时,可以实现CacheManagerCustomizer接口,指定泛型为需要进行自定义的CacheManager实现类,然后把它定义为一个Spring bean。通过实现这个接口,你可以对Spring的CacheManager进行自定义扩展,例如配置缓存策略、设置缓存过期时间等。</p>
<p>这个接口的使用可以帮助开发者更好地控制和优化缓存的行为,提高应用程序的性能和响应速度。在实现自定义扩展时,可以使用Spring的注解或XML配置来定义自定义逻辑,并根据需要选择是否将自定义的逻辑应用到所有CacheManager实现上,或者只应用到特定的CacheManager实现上。</p></li></ul>
<div class="jb51code"><pre class="brush:java;">@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生成策略
};
}
}
</pre></div>
<ul><li><strong>使用缓存注解</strong>:<br />在你的服务类中的方法上使用 Spring 的缓存注解,例如 <code>@Cacheable</code>, <code>@CacheEvict</code>, <code>@CachePut</code> 等。这样,当这些方法被调用时,它们将与 Redis 缓存进行交互。</li><li><strong>自定义序列化</strong>:<br />如果你需要自定义序列化,你可以创建一个配置类并实现 <code>RedisSerializer</code> 接口。然后,你可以在 Redis 的相关配置中指定这个序列化器。</li></ul>
<div class="jb51code"><pre class="brush:java;">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);
}
</pre></div>
<p class="maodian"></p><h3>3、使用示例</h3>
<p><strong>1、创建测试Service</strong></p>
<div class="jb51code"><pre class="brush:java;">@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;
}
}
</pre></div>
<p><strong>2、创建测试类</strong></p>
<div class="jb51code"><pre class="brush:java;">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());
}
}
</pre></div>
<p>执行结果如下:</p>
<blockquote><p>data for k<br />data for k<br />data for k<br />StopWatch 'getData': 1.3141034 seconds<br />----------------------------------------<br />Seconds % Task name<br />----------------------------------------<br />1.3104986 100% 1<br />0.0029345 00% 2<br />0.0006703 00% 3</p></blockquote>
<p>可以看见,只有第一次执行耗时,后面两次直接从缓存读取,几乎没有耗时</p>
<p class="maodian"></p><h2>参考</h2>
<ul><li>spring-boot-starter-cache</li><li>spring-boot-starter-redis</li></ul>
<p>到此这篇关于SpringBoot3.0集成Redis缓存的实现示例的文章就介绍到这了,更多相关SpringBoot集成Redis缓存内容请搜索琼殿技术社区以前的文章或继续浏览下面的相关文章希望大家以后多多支持琼殿技术社区! </p>
<div class="art_xg">
<b>您可能感兴趣的文章:</b><ul><li>SpringBoot整合Redis实现token缓存</li><li>SpringBoot结合Redis实现缓存管理功能</li><li>SpringBoot整合redis使用缓存注解详解</li><li>SpringBoot+MyBatis+Redis实现分布式缓存</li><li>springboot使用redis注解做缓存的基本操作方式</li><li>SpringBoot中Redis的缓存更新策略详解</li><li>springboot整合ehcache和redis实现多级缓存实战案例</li><li>SpringBoot结合Redis实现缓存</li><li>SpringBoot使用Redis实现分布式缓存</li><li>SpringBoot中的Redis 缓存问题及操作方法</li></ul>
</div>
</div>
<!--endmain-->
頁:
[1]