SpringBoot缓存技术整合SpringData Redis

Posted --->别先生<---

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringBoot缓存技术整合SpringData Redis相关的知识,希望对你有一定的参考价值。

首先说明一下,这里使用的是Springboot2.2.6.RELEASE版本,由于Springboot迭代很快,所以要注意版本问题。

1、SpringData Redis是属于SpringData下的一个模块。作用就是简化对于redis的操作。SpringData JPA为了简化对数据库的操作。修改pom文件添加SpringData Redis的坐标。

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 3          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
 4     <modelVersion>4.0.0</modelVersion>
 5     <parent>
 6         <groupId>org.springframework.boot</groupId>
 7         <artifactId>spring-boot-starter-parent</artifactId>
 8         <version>2.2.6.RELEASE</version>
 9         <relativePath/> <!-- lookup parent from repository -->
10     </parent>
11     <groupId>com.bie.springboot</groupId>
12     <artifactId>springdata-redis</artifactId>
13     <version>0.0.1-SNAPSHOT</version>
14     <name>springdata-redis</name>
15     <description>Demo project for Spring Boot</description>
16 
17     <properties>
18         <java.version>1.8</java.version>
19     </properties>
20 
21     <dependencies>
22         <!-- thymeleaf的启动器 -->
23         <dependency>
24             <groupId>org.springframework.boot</groupId>
25             <artifactId>spring-boot-starter-thymeleaf</artifactId>
26         </dependency>
27         <!-- springBoot的启动器 -->
28         <dependency>
29             <groupId>org.springframework.boot</groupId>
30             <artifactId>spring-boot-starter-web</artifactId>
31         </dependency>
32 
33         <!-- springBoot测试的启动器 -->
34         <dependency>
35             <groupId>org.springframework.boot</groupId>
36             <artifactId>spring-boot-starter-test</artifactId>
37             <scope>test</scope>
38             <!--<exclusions>
39                 <exclusion>
40                     <groupId>org.junit.vintage</groupId>
41                     <artifactId>junit-vintage-engine</artifactId>
42                 </exclusion>
43             </exclusions>-->
44         </dependency>
45         <!-- SpringData Redis的启动器 -->
46         <dependency>
47             <groupId>org.springframework.boot</groupId>
48             <artifactId>spring-boot-starter-data-redis</artifactId>
49         </dependency>
50         <!-- jedis是操作redis的工具依赖包 -->
51         <dependency>
52             <groupId>redis.clients</groupId>
53             <artifactId>jedis</artifactId>
54             <version>2.9.0</version>
55         </dependency>
56     </dependencies>
57 
58     <build>
59         <plugins>
60             <plugin>
61                 <groupId>org.springframework.boot</groupId>
62                 <artifactId>spring-boot-maven-plugin</artifactId>
63             </plugin>
64         </plugins>
65     </build>
66 
67 </project>

编写SpringData Redis的配置类,替代了之前的配置文件。

  1 package com.bie.springboot.config;
  2 
  3 import org.springframework.context.annotation.Bean;
  4 import org.springframework.context.annotation.Configuration;
  5 import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
  6 import org.springframework.data.redis.connection.jedis.JedisClientConfiguration;
  7 import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
  8 import org.springframework.data.redis.core.RedisTemplate;
  9 import org.springframework.data.redis.serializer.StringRedisSerializer;
 10 import redis.clients.jedis.JedisPoolConfig;
 11 
 12 /**
 13  * 完成对Redis的整合的一些配置。
 14  * 1、JedisConnectionFacotory从SpringData Redis 2.0开始已经不推荐直接显示设置连接的信息了,
 15  * 一方面为了使配置信息与建立连接工厂解耦,另一方面抽象出Standalone、Sentinel、RedisCluster
 16  * 三种模式的环境配置类和一个统一的jedis客户端连接配置类(用于配置连接池和SSL连接),
 17  * 使得我们可以更加灵活方便根据实际业务场景需要来配置连接信息。
 18  */
 19 @Configuration
 20 public class RedisConfig {
 21 
 22     /**
 23      * 1.创建JedisPoolConfig对象。在该对象中完成一些链接池配置,连接池配置信息。
 24      *
 25      * @return
 26      */
 27     @Bean
 28     public JedisPoolConfig jedisPoolConfig() {
 29         // 创建JedisPoolConfig对象
 30         JedisPoolConfig config = new JedisPoolConfig();
 31         // 最大空闲数
 32         config.setMaxIdle(10);
 33         // 最小空闲数
 34         config.setMinIdle(5);
 35         // 最大链接数
 36         config.setMaxTotal(20);
 37         //当池内没有可用的连接时,最大等待时间
 38         config.setMaxWaitMillis(10000);
 39         return config;
 40     }
 41 
 42     /**
 43      * 2.创建JedisConnectionFactory,配置redis链接信息。
 44      *
 45      * @param config 从IOC容器中将连接池拿去出来
 46      * @return
 47      */
 48     @Bean
 49     public JedisConnectionFactory jedisConnectionFactory(JedisPoolConfig config) {
 50         // 关联链接池的配置对象,不推荐使用了
 51         // factory.setPoolConfig(config);
 52         // 配置链接Redis的信息
 53         // 主机地址,不推荐使用了
 54         // factory.setHostName("192.168.70.128");
 55         // 端口,不推荐使用了
 56         // factory.setPort(6379);
 57 
 58         // 创建RedisStandaloneConfiguration对象
 59         RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration();
 60         // 然后根据该配置实例来初始化jedis连接工厂。
 61         // 设置ip主机地址
 62         redisStandaloneConfiguration.setHostName("192.168.110.140");
 63         // 设置在第几号redis数据库操作,默认操作第0个数据库
 64         redisStandaloneConfiguration.setDatabase(0);
 65         // 设置redis的密码
 66         // redisStandaloneConfiguration.setPassword(RedisPassword.of("123456"));
 67         // 设置端口号
 68         redisStandaloneConfiguration.setPort(6379);
 69 
 70 
 71         // 获得默认的连接池构造器
 72         JedisClientConfiguration.JedisPoolingClientConfigurationBuilder jpcb = JedisClientConfiguration.builder().usePooling();
 73 
 74         // 指定jedisPoolConifig来修改默认的连接池构造器
 75         jpcb.poolConfig(config);
 76         // 通过构造器来构造jedis客户端配置
 77         JedisClientConfiguration jedisClientConfiguration = jpcb.build();
 78 
 79         // 将设置好的数据库链接传递到JedisConnectionFactory构造方法里面
 80         // JedisConnectionFactory factory = new JedisConnectionFactory(redisStandaloneConfiguration);
 81 
 82         // 返回,注入到ioc容器中
 83         // 单机配置 + 客户端配置 = jedis连接工厂
 84         return new JedisConnectionFactory(redisStandaloneConfiguration, jedisClientConfiguration);
 85     }
 86 
 87 
 88     /**
 89      * 3.创建RedisTemplate模板对象,用于执行Redis操作的方法。
 90      *
 91      * @param jedisConnectionFactory
 92      *
 93      * @return
 94      */
 95     @Bean
 96     public RedisTemplate<String, Object> redisTemplate(JedisConnectionFactory jedisConnectionFactory) {
 97         // 创建RedisTemplate对象
 98         RedisTemplate<String, Object> template = new RedisTemplate<>();
 99         // 关联,链接连接池工厂,RedisTemplate与JedisConnectionFactory关联
100         template.setConnectionFactory(jedisConnectionFactory);
101         // 为key设置序列化器
102         template.setKeySerializer(new StringRedisSerializer());
103         // 为value设置序列化器
104         template.setValueSerializer(new StringRedisSerializer());
105         return template;
106     }
107 
108 
109     /**
110      * jedis连接工厂
111      *
112      * @param jedisPoolConfig
113      * @return
114      */
115 //    @Bean
116 //    public RedisConnectionFactory redisConnectionFactory(JedisPoolConfig jedisPoolConfig) {
117 //        // 单机版jedis
118 //        RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration();
119 //        // 设置redis服务器的host或者ip地址
120 //        redisStandaloneConfiguration.setHostName("192.168.110.140");
121 //        // 设置默认使用的数据库
122 //        redisStandaloneConfiguration.setDatabase(0);
123 //        // 设置密码
124 //        // redisStandaloneConfiguration.setPassword(RedisPassword.of("123456"));
125 //        // 设置redis的服务的端口号
126 //        redisStandaloneConfiguration.setPort(6379);
127 //        // 获得默认的连接池构造器
128 //        // JedisClientConfiguration.JedisPoolingClientConfigurationBuilder jpcb = (JedisClientConfiguration.JedisPoolingClientConfigurationBuilder) JedisClientConfiguration.builder();
129 //
130 //        // 获得默认的连接池构造器
131 //        JedisClientConfiguration.JedisPoolingClientConfigurationBuilder jpcb = JedisClientConfiguration.builder().usePooling();
132 //
133 //        // 指定jedisPoolConifig来修改默认的连接池构造器
134 //        jpcb.poolConfig(jedisPoolConfig);
135 //        // 通过构造器来构造jedis客户端配置
136 //        JedisClientConfiguration jedisClientConfiguration = jpcb.build();
137 //        // 单机配置 + 客户端配置 = jedis连接工厂
138 //        return new JedisConnectionFactory(redisStandaloneConfiguration, jedisClientConfiguration);
139 //    }
140 
141 
142 }

编写测试代码,测试整合环境。

 1 package com.bie.springboot;
 2 
 3 import org.junit.jupiter.api.Test;
 4 import org.junit.runner.RunWith;
 5 import org.springframework.beans.factory.annotation.Autowired;
 6 import org.springframework.boot.test.context.SpringBootTest;
 7 import org.springframework.data.redis.core.RedisTemplate;
 8 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
 9 
10 @RunWith(SpringJUnit4ClassRunner.class)
11 @SpringBootTest(classes = SpringdataRedisApplication.class)
12 class SpringdataRedisApplicationTests {
13 
14     @Autowired
15     private RedisTemplate<String, Object> redisTemplate;
16 
17     /*** 添加一个字符串 */
18     @Test
19     public void testSet() {
20         this.redisTemplate.opsForValue().set("key", "我想要学好springboot");
21     }
22 
23     /*** 获取一个字符串 */
24     @Test
25     public void testGet() {
26         String value = (String) this.redisTemplate.opsForValue().get("key");
27         System.out.println(value);
28     }
29 
30 }

如果报了下面所示的错误,如下所示:

  1   .   ____          _            __ _ _
  2  /\\\\ / ___\'_ __ _ _(_)_ __  __ _ \\ \\ \\ \\
  3 ( ( )\\___ | \'_ | \'_| | \'_ \\/ _` | \\ \\ \\ \\
  4  \\\\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  5   \'  |____| .__|_| |_|_| |_\\__, | / / / /
  6  =========|_|==============|___/=/_/_/_/
  7  :: Spring Boot ::        (v2.2.6.RELEASE)
  8 
  9 2020-05-16 23:19:54.910  INFO 5476 --- [           main] c.b.s.SpringdataRedisApplicationTests    : Starting SpringdataRedisApplicationTests on DESKTOP-V37QSSE with PID 5476 (started by biehl in D:\\program\\idea\\IntelliJ IDEA 2019.1.3\\workspace_idea\\springdata-redis)
 10 2020-05-16 23:19:54.914  INFO 5476 --- [           main] c.b.s.SpringdataRedisApplicationTests    : No active profile set, falling back to default profiles: default
 11 2020-05-16 23:19:56.826  INFO 5476 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Multiple Spring Data modules found, entering strict repository configuration mode!
 12 2020-05-16 23:19:56.830  INFO 5476 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data Redis repositories in DEFAULT mode.
 13 2020-05-16 23:19:56.887  INFO 5476 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 29ms. Found 0 Redis repository interfaces.
 14 2020-05-16 23:19:57.186 ERROR 5476 --- [           main] o.s.boot.SpringApplication               : Application run failed
 15 
 16 java.lang.NoClassDefFoundError: redis/clients/jedis/util/Pool
 17     at java.lang.Class.getDeclaredConstructors0(Native Method) ~[na:1.8.0_191]
 18     at java.lang.Class.privateGetDeclaredConstructors(Class.java:2671) ~[na:1.8.0_191]
 19     at java.lang.Class.getDeclaredConstructors(Class.java:2020) ~[na:1.8.0_191]
 20     at org.springframework.boot.context.properties.ConfigurationPropertiesBindConstructorProvider.findConstructorBindingAnnotatedConstructor(ConfigurationPropertiesBindConstructorProvider.java:62) ~[spring-boot-2.2.6.RELEASE.jar:2.2.6.RELEASE]
 21     at org.springframework.boot.context.properties.ConfigurationPropertiesBindConstructorProvider.getBindConstructor(ConfigurationPropertiesBindConstructorProvider.java:48) ~[spring-boot-2.2.6.RELEASE.jar:2.2.6.RELEASE]
 22     at org.springframework.boot.context.properties.ConfigurationPropertiesBean$BindMethod.forType(ConfigurationPropertiesBean.java:311) ~[spring-boot-2.2.6.RELEASE.jar:2.2.6.RELEASE]
 23     at org.springframework.boot.context.properties.ConfigurationPropertiesBeanDefinitionValidator.validate(ConfigurationPropertiesBeanDefinitionValidator.java:63) ~[spring-boot-2.2.6.RELEASE.jar:2.2.6.RELEASE]
 24     at org.springframework.boot.context.properties.ConfigurationPropertiesBeanDefinitionValidator.postProcessBeanFactory(ConfigurationPropertiesBeanDefinitionValidator.java:45) ~[spring-boot-2.2.6.RELEASE.jar:2.2.6.RELEASE]
 25     at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:286) ~[spring-context-5.2.5.RELEASE.jar:5.2.5.RELEASE]
 26     at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:174) ~[spring-context-5.2.5.RELEASE.jar:5.2.5.RELEASE]
 27     at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:706) ~[spring-context-5.2.5.RELEASE.jar:5.2.5.RELEASE]
 28     at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:532) ~[spring-context-5.2.5.RELEASE.jar:5.2.5.RELEASE]
 29     at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:747) ~[spring-boot-2.2.6.RELEASE.jar:2.2.6.RELEASE]
 30     at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) ~[spring-boot-2.2.6.RELEASE.jar:2.2.6.RELEASE]
 31     at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) ~[spring-boot-2.2.6.RELEASE.jar:2.2.6.RELEASE]
 32     at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:126) [spring-boot-test-2.2.6.RELEASE.jar:2.2.6.RELEASE]
 33     at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:99) [spring-test-5.2.5.RELEASE.jar:5.2.5.RELEASE]
 34     at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124) [spring-test-5.2.5.RELEASE.jar:5.2.5.RELEASE]
 35     at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:123) [spring-test-5.2.5.RELEASE.jar:5.2.5.RELEASE]
 36     at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:190) [spring-test-5.2.5.RELEASE.jar:5.2.5.RELEASE]
 37     at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:132) [spring-test-5.2.5.RELEASE.jar:5.2.5.RELEASE]
 38     at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:244) [spring-test-5.2.5.RELEASE.jar:5.2.5.RELEASE]
 39     at org.springframework.test.context.junit.jupiter.SpringExtension.postProcessTestInstance(SpringExtension.java:98) [spring-test-5.2.5.RELEASE.jar:5.2.5.RELEASE]
 40     at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$invokeTestInstancePostProcessors$5(ClassBasedTestDescriptor.java:337) [junit-jupiter-engine-5.5.2.jar:5.5.2]
 41     at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.executeAndMaskThrowable(ClassBasedTestDescriptor.java:342) [junit-jupiter-engine-5.5.2.jar:5.5.2]
 42     at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$invokeTestInstancePostProcessors$6(ClassBasedTestDescriptor.java:337) [junit-jupiter-engine-5.5.2.jar:5.5.2]
 43     at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193) ~[na:1.8.0_191]
 44     at java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:175) ~[na:1.8.0_191]
 45     at java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1382) ~[na:1.8.0_191]
 46     at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481) ~[na:1.8.0_191]
 47     at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471) ~[na:1.8.0_191]
 48     at java.util.stream.StreamSpliterators$WrappingSpliterator.forEachRemaining(StreamSpliterators.java:312) ~[na:1.8.0_191]
 49     at java.util.stream.Streams$ConcatSpliterator.forEachRemaining(Streams.java:743) ~[na:1.8.0_191]
 50     at java.util.stream.Streams$ConcatSpliterator.forEachRemaining(Streams.java:742) ~[na:1.8.0_191]
 51     at java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:580) ~[na:1.8.0_191]
 52     at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.invokeTestInstancePostProcessors(ClassBasedTestDescriptor.java:336) [junit-jupiter-engine-5.5.2.jar:5.5.2]
 53     at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.instantiateAndPostProcessTestInstance(ClassBasedTestDescriptor.java:259) [junit-jupiter-engine-5.5.2.jar:5.5.2]
 54     at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$testInstancesProvider$2(ClassBasedTestDescriptor.java:252) [junit-jupiter-engine-5.5.2.jar:5.5.2]
 55     at java.util.Optional.orElseGet(Optional.java:267) ~[na:1.8.0_191]
 56     at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$testInstancesProvider$3(ClassBasedTestDescriptor.java:251) [junit-jupiter-engine-5.5.2.jar:5.5.2]
 57     at org.junit.jupiter.engine.execution.TestInstancesProvider.getTestInstances(TestInstancesProvider.java:29) ~[junit-jupiter-engine-5.5.2.jar:5.5.2]
 58     at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$prepare$0(TestMethodTestDescriptor.java:106) ~[junit-jupiter-engine-5.5.2.jar:5.5.2]
 59     at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) ~[junit-platform-engine-1.5.2.jar:1.5.2]
 60     at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.prepare(TestMethodTestDescriptor.java:105) ~[junit-jupiter-engine-5.5.2.jar:5.5.2]
 61     at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.prepare(TestMethodTestDescriptor.java:69) ~[junit-jupiter-engine-5.5.2.jar:5.5.2]
 62     at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$prepare$1(NodeTestTask.java:107) ~[junit-platform-engine-1.5.2.jar:1.5.2]
 63     at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) ~[junit-platform-engine-1.5.2.jar:1.5.2]
 64     at org.junit.platform.engine.support.hierarchical.NodeTestTask.prepare(NodeTestTask.java:107) ~[junit-platform-engine-1.5.2.jar:1.5.2]
SpringBoot2 整合Ehcache组件,轻量级缓存管理

SpringBoot整合SpringSeesion实现Redis缓存

springboot整合redis缓存一些知识点

SpringBoot整合Redis,一篇解决缓存的所有问题

SpringBoot整合Redis,一篇解决缓存的所有问题

SpringBoot整合Redis,一篇解决缓存的所有问题