1、Redis是当下最流行的用于实现缓存机制的NoSQL数据库,其主要通过key-value存储,支持高并发访问。在实际工作中,Redis结合SpringData技术后可以方便地实现序列化对象的存储。SpringBoot很好地支持了Redis,可以在项目中使用SpringData进行Redis数据操作。
SpringBoot整合RedisTemplate操作Redis,RedisTemplate是SpringData提供的Redis操作模板,该操作模板主要以Jedis驱动程序为实现基础,进行数据操作封装,所以可以直接调用Redis中的各种数据处理命令进行数据库操作。
修改项目中的pom.xml配置文件,追加Redis的依赖引用,如下所示:
1 <?xml version="1.0" encoding="UTF-8"?>
2 <project xmlns="http://maven.apache.org/POM/4.0.0"
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
5 https://maven.apache.org/xsd/maven-4.0.0.xsd">
6 <modelVersion>4.0.0</modelVersion>
7 <parent>
8 <groupId>org.springframework.boot</groupId>
9 <artifactId>spring-boot-starter-parent</artifactId>
10 <version>2.3.5.RELEASE</version>
11 <relativePath /> <!-- lookup parent from repository -->
12 </parent>
13 <groupId>com.example</groupId>
14 <artifactId>demo</artifactId>
15 <version>0.0.1-SNAPSHOT</version>
16 <name>demo</name>
17 <description>Demo project for Spring Boot</description>
18
19 <properties>
20 <java.version>1.8</java.version>
21 <maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>
22 </properties>
23
24 <dependencies>
25 <dependency>
26 <groupId>org.springframework.boot</groupId>
27 <artifactId>spring-boot-starter-web</artifactId>
28 </dependency>
29
30 <dependency>
31 <groupId>org.springframework.boot</groupId>
32 <artifactId>spring-boot-starter-test</artifactId>
33 <scope>test</scope>
34 <exclusions>
35 <exclusion>
36 <groupId>org.junit.vintage</groupId>
37 <artifactId>junit-vintage-engine</artifactId>
38 </exclusion>
39 </exclusions>
40 </dependency>
41
42 <!-- mysql驱动包 -->
43 <dependency>
44 <groupId>mysql</groupId>
45 <artifactId>mysql-connector-java</artifactId>
46 </dependency>
47
48 <!-- druid连接池 -->
49 <dependency>
50 <groupId>com.alibaba</groupId>
51 <artifactId>druid</artifactId>
52 <version>1.1.10</version>
53 </dependency>
54
55 <dependency>
56 <groupId>org.springframework.boot</groupId>
57 <artifactId>spring-boot-starter-data-jpa</artifactId>
58 </dependency>
59 <dependency>
60 <groupId>org.springframework.boot</groupId>
61 <artifactId>spring-boot-starter-cache</artifactId>
62 </dependency>
63 <dependency>
64 <groupId>org.hibernate</groupId>
65 <artifactId>hibernate-ehcache</artifactId>
66 </dependency>
67 <!-- redis -->
68 <dependency>
69 <groupId>org.springframework.boot</groupId>
70 <artifactId>spring-boot-starter-data-redis</artifactId>
71 <!-- 1.5的版本默认采用的连接池技术是jedis,2.0以上版本默认连接池是lettuce, 因为此次是采用jedis,所以需要排除lettuce的jar -->
72 <exclusions>
73 <exclusion>
74 <groupId>redis.clients</groupId>
75 <artifactId>jedis</artifactId>
76 </exclusion>
77 <exclusion>
78 <groupId>io.lettuce</groupId>
79 <artifactId>lettuce-core</artifactId>
80 </exclusion>
81 </exclusions>
82 </dependency>
83
84 <!-- jedis客户端 -->
85 <dependency>
86 <groupId>redis.clients</groupId>
87 <artifactId>jedis</artifactId>
88 </dependency>
89
90 <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-pool2 -->
91 <!-- spring2.X集成redis所需common-pool2,使用jedis必须依赖它 -->
92 <dependency>
93 <groupId>org.apache.commons</groupId>
94 <artifactId>commons-pool2</artifactId>
95 </dependency>
96 </dependencies>
97
98 <build>
99 <plugins>
100 <plugin>
101 <groupId>org.springframework.boot</groupId>
102 <artifactId>spring-boot-maven-plugin</artifactId>
103 </plugin>
104 </plugins>
105 <resources>
106 <resource>
107 <directory>src/main/resources</directory>
108 <includes>
109 <include>**/*.properties</include>
110 <include>**/*.yml</include>
111 <include>**/*.xml</include>
112 <include>**/*.p12</include>
113 <include>**/*.html</include>
114 <include>**/*.jpg</include>
115 <include>**/*.png</include>
116 </includes>
117 </resource>
118 </resources>
119 </build>
120
121 </project>
这里要说明一下,因为我使用的SpringBoot是2.X,Redis是3.3.0,SpringBoot2.X默认采用lettuce,而SpringBoot1.5默认采用的是jdeis,这里是使用的jedis,所以在依赖里要排除lettuce。否则会报错:
1 . ____ _ __ _ _
2 /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
3 ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
4 \\/ ___)| |_)| | | | | || (_| | ) ) ) )
5 ' |____| .__|_| |_|_| |_\__, | / / / /
6 =========|_|==============|___/=/_/_/_/
7 :: Spring Boot :: (v2.3.5.RELEASE)
8
9 2020-11-23 11:09:23.145 INFO 53736 --- [ main] com.demo.DemoApplication : Starting DemoApplication on DESKTOP-T450s with PID 53736 (D:\eclipse\workspace_spring\demo\target\classes started by Aiyufei in D:\eclipse\workspace_spring\demo)
10 2020-11-23 11:09:23.150 INFO 53736 --- [ main] com.demo.DemoApplication : No active profile set, falling back to default profiles: default
11 2020-11-23 11:09:24.343 INFO 53736 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Multiple Spring Data modules found, entering strict repository configuration mode!
12 2020-11-23 11:09:24.344 INFO 53736 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFERRED mode.
13 2020-11-23 11:09:24.475 INFO 53736 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 117ms. Found 1 JPA repository interfaces.
14 2020-11-23 11:09:24.503 INFO 53736 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Multiple Spring Data modules found, entering strict repository configuration mode!
15 2020-11-23 11:09:24.505 INFO 53736 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data Redis repositories in DEFAULT mode.
16 2020-11-23 11:09:24.528 INFO 53736 --- [ main] .RepositoryConfigurationExtensionSupport : Spring Data Redis - Could not safely identify store assignment for repository candidate interface com.demo.dao.UserDao. If you want this repository to be a Redis repository, consider annotating your entities with one of these annotations: org.springframework.data.redis.core.RedisHash (preferred), or consider extending one of the following types with your repository: org.springframework.data.keyvalue.repository.KeyValueRepository.
17 2020-11-23 11:09:24.529 INFO 53736 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 11ms. Found 0 Redis repository interfaces.
18 2020-11-23 11:09:25.650 INFO 53736 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
19 2020-11-23 11:09:25.661 INFO 53736 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
20 2020-11-23 11:09:25.661 INFO 53736 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.39]
21 2020-11-23 11:09:25.834 INFO 53736 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
22 2020-11-23 11:09:25.835 INFO 53736 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 2596 ms
23 2020-11-23 11:09:26.067 INFO 53736 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
24 2020-11-23 11:09:26.119 INFO 53736 --- [ task-1] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
25 2020-11-23 11:09:26.257 INFO 53736 --- [ task-1] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.4.22.Final
26 2020-11-23 11:09:26.331 WARN 53736 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'springBootController': Unsatisfied dependency expressed through field 'redisTemplate'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'stringRedisTemplate' defined in class path resource [org/springframework/boot/autoconfigure/data/redis/RedisAutoConfiguration.class]: Unsatisfied dependency expressed through method 'stringRedisTemplate' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'redisConnectionFactory' defined in class path resource [org/springframework/boot/autoconfigure/data/redis/LettuceConnectionConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory]: Factory method 'redisConnectionFactory' threw exception; nested exception is java.lang.NoClassDefFoundError: io/netty/handler/ssl/SslProvider
27 2020-11-23 11:09:26.351 INFO 53736 --- [ main] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
28 2020-11-23 11:09:26.632 INFO 53736 --- [ task-1] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {
5.1.0.Final}
29 Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
30 2020-11-23 11:09:26.962 INFO 53736 --- [ task-1] com.alibaba.druid.pool.DruidDataSource : {dataSource-1} inited
31 2020-11-23 11:09:27.189 INFO 53736 --- [ task-1] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL57Dialect
32 2020-11-23 11:09:28.105 INFO 53736 --- [ task-1] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
33 2020-11-23 11:09:28.114 INFO 53736 --- [ task-1] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
34 2020-11-23 11:09:28.118 INFO 53736 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService 'applicationTaskExecutor'
35 2020-11-23 11:09:28.125 INFO 53736 --- [ main] com.alibaba.druid.pool.DruidDataSource : {dataSource-1} closed
36 2020-11-23 11:09:28.127 INFO 53736 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
37 2020-11-23 11:09:28.140 INFO 53736 --- [ main] ConditionEvaluationReportLoggingListener :
38
39 Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
40 2020-11-23 11:09:28.155 ERROR 53736 --- [ main] o.s.boot.SpringApplication : Application run failed
41
42 org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'springBootController': Unsatisfied dependency expressed through field 'redisTemplate'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'stringRedisTemplate' defined in class path resource [org/springframework/boot/autoconfigure/data/redis/RedisAutoConfiguration.class]: Unsatisfied dependency expressed through method 'stringRedisTemplate' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'redisConnectionFactory' defined in class path resource [org/springframework/boot/autoconfigure/data/redis/LettuceConnectionConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory]: Factory method 'redisConnectionFactory' threw exception; nested exception is java.lang.NoClassDefFoundError: io/netty/handler/ssl/SslProvider
43 at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:643) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE]
44 at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:130) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE]
45 at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:399) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE]
46 at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1420) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE]
47 at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:593) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE]
48 at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:516) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE]
49 at org.springframework.beans.factory