SpringBoot2.x整合Redis数据库
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.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:324) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE] 50 at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE] 51 at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:322) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE] 52 at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE] 53 at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:897) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE] 54 at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:879) ~[spring-context-5.2.10.RELEASE.jar:5.2.10.RELEASE] 55 at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:551) ~[spring-context-5.2.10.RELEASE.jar:5.2.10.RELEASE] 56 at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:143) ~[spring-boot-2.3.5.RELEASE.jar:2.3.5.RELEASE] 57 at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:758) [spring-boot-2.3.5.RELEASE.jar:2.3.5.RELEASE] 58 at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:750) [spring-boot-2.3.5.RELEASE.jar:2.3.5.RELEASE] 59 at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:405) [spring-boot-2.3.5.RELEASE.jar:2.3.5.RELEASE] 60 at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) [spring-boot-2.3.5.RELEASE.jar:2.3.5.RELEASE] 61 at org.springframework.boot.SpringApplication.run(SpringApplication.java:1237) [spring-boot-2.3.5.RELEASE.jar:2.3.5.RELEASE] 62 at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226) [spring-boot-2.3.5.RELEASE.jar:2.3.5.RELEASE] 63 at com.demo.DemoApplication.main(DemoApplication.java:11) [classes/:na] 64 Caused by: 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 65 at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:797) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE] 66 at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:538) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE] 67 at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1336) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE] 68 at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1176) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE] 69 at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:556) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE] 70 at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:516) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE] 71 at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:324) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE] 72 at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE] 73 at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:322) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE] 74 at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE] 75 at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:276) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE] 76 at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1307) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE] 77 at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1227) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE] 78 at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:640) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE] 79 ... 20 common frames omitted 80 Caused by: 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 81 at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:655) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE] 82 at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:635) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE] 83 at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1336) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE] 84 at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1176) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE] 85 at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:556) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE] 86 at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:516) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE] 87 at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:324) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE] 88 at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE] 89 at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:322) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE] 90 at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE] 91 at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:276) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE] 92 at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1307) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE] 93 at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1227) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE] 94 at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:884) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE] 95 at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:788) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE] 96 ... 33 common frames omitted 97 Caused by: 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 98 at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE] 99 at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:650) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE] 100 ... 47 common frames omitted 101 Caused by: java.lang.NoClassDefFoundError: io/netty/handler/ssl/SslProvider 102 at io.lettuce.core.SslOptions.<clinit>(SslOptions.java:52) ~[lettuce-core-5.3.5.RELEASE.jar:5.3.5.RELEASE] 103 at io.lettuce.core.ClientOptions.<clinit>(ClientOptions.java:48) ~[lettuce-core-5.3.5.RELEASE.jar:5.3.5.RELEASE] 104 at org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration$LettuceClientConfigurationBuilder.<init>(LettuceClientConfiguration.java:167) ~[spring-data-redis-2.3.5.RELEASE.jar:2.3.5.RELEASE] 105 at org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration$LettucePoolingClientConfigurationBuilder.<init>(LettucePoolingClientConfiguration.java:97) ~[spring-data-redis-2.3.5.RELEASE.jar:2.3.5.RELEASE] 106 at org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration.builder(LettucePoolingClientConfiguration.java:51) ~[spring-data-redis-2.3.5.RELEASE.jar:2.3.5.RELEASE] 107 at org.springframework.boot.autoconfigure.data.redis.LettuceConnectionConfiguration$PoolBuilderFactory.createBuilder(LettuceConnectionConfiguration.java:159) ~[spring-boot-autoconfigure-2.3.5.RELEASE.jar:2.3.5.RELEASE] 108 at org.springframework.boot.autoconfigure.data.redis.LettuceConnectionConfiguration.createBuilder(LettuceConnectionConfiguration.java:107) ~[spring-boot-autoconfigure-2.3.5.RELEASE.jar:2.3.5.RELEASE] 109 at org.springframework.boot.autoconfigure.data.redis.LettuceConnectionConfiguration.getLettuceClientConfiguration(LettuceConnectionConfiguration.java:92) ~[spring-boot-autoconfigure-2.3.5.RELEASE.jar:2.3.5.RELEASE] 110 at org.springframework.boot.autoconfigure.data.redis.LettuceConnectionConfiguration.redisConnectionFactory(LettuceConnectionConfiguration.java:74) ~[spring-boot-autoconfigure-2.3.5.RELEASE.jar:2.3.5.RELEASE] 111 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_161] 112 at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_161] 113 at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_161] 114 at java.lang.reflect.Method.invoke(Unknown Source) ~[na:1.8.0_161] 115 at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE] 116 ... 48 common frames omitted 117 Caused by: java.lang.ClassNotFoundException: io.netty.handler.ssl.SslProvider 118 at java.net.URLClassLoader$1.run(Unknown Source) ~[na:1.8.0_161] 119 at java.net.URLClassLoader$1.run(Unknown Source) ~[na:1.8.0_161] 120 at java.security.AccessController.doPrivileged(Native Method) ~[na:1.8.0_161] 121 at java.net.URLClassLoader.findClass(Unknown Source) ~[na:1.8.0_161] 122 at java.lang.ClassLoader.loadClass(Unknown Source) ~[na:1.8.0_161] 123 at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) ~[na:1.8.0_161] 124 at java.lang.ClassLoader.loadClass(Unknown Source) ~[na:1.8.0_161] 125 ... 62 common frames omitted 126 Caused by: java.util.zip.ZipException: invalid LOC header (bad signature) 127 at java.util.zip.ZipFile.read(Native Method) ~[na:1.8.0_161] 128 at java.util.zip.ZipFile.access$1400(Unknown Source) ~[na:1.8.0_161] 129 at java.util.zip.ZipFile$ZipFileInputStream.read(Unknown Source) ~[na:1.8.0_161] 130 at java.util.zip.ZipFile$ZipFileInflaterInputStream.fill(Unknown Source) ~[na:1.8.0_161] 131 at java.util.zip.InflaterInputStream.read(Unknown Source) ~[na:1.8.0_161] 132 at java.util.jar.Manifest$FastInputStream.fill(Unknown Source) ~[na:1.8.0_161] 133 at java.util.jar.Manifest$FastInputStream.readLine(Unknown Source) ~[na:1.8.0_161] 134 at java.util.jar.Manifest$FastInputStream.readLine(Unknown Source) ~[na:1.8.0_161] 135 at java.util.jar.Attributes.read(Unknown Source) ~[na:1.8.0_161] 136 at java.util.jar.Manifest.read(Unknown Source) ~[na:1.8.0_161] 137 at java.util.jar.Manifest.<init>(Unknown Source) ~[na:1.8.0_161] 138 at java.util.jar.JarFile.getManifestFromReference(Unknown Source) ~[na:1.8.0_161] 139 at java.util.jar.JarFile.getManifest(Unknown Source) ~[na:1.8.0_161] 140 at sun.misc.URLClassPath$JarLoader$2.getManifest(Unknown Source) ~[na:1.8.0_161] 141 at java.net.URLClassLoader.defineClass(Unknown Source) ~[na:1.8.0_161] 142 at java.net.URLClassLoader.access$100(Unknown Source) ~[na:1.8.0_161] 143 ... 69 common frames omitted
修改application.yml配置文件,引入Redis相关配置项,如下所示:
1 # Redis的相关配置,主机名称 2 spring.redis.host=192.168.110.140 3 # 端口号 4 spring.redis.port=6379 5 # 认证密码 6 spring.redis.password= 7 # 连接超时时间 8 spring.redis.timeout=1000 9 # 默认数据库 10 spring.redis.database=0 11 # 连接池配置,最大连接数 12 spring.redis.jedis.pool.max-active=10 13 # 最大维持连接数 14 spring.redis.jedis.pool.max-idle=8 15 # 最小维持连接数 16 spring.redis.jedis.pool.min-idle=2 17 # 最大等待连接超时时间 18 spring.redis.jedis.pool.max-wait=100
搞一个控制类,在方法中直接注入了RedisTemplate模板对象,并且利用模板对象中提供的方法实现了key-value数据的保存与获取。
1 package com.demo.controller; 2 3 import org.springframework.beans.factory.annotation.Autowired; 4 import org.springframework.data.redis.core.RedisTemplate; 5 import org.springframework.stereotype.Controller; 6 import org.springframework.web.bind.annotation.RequestMapping; 7 import org.springframework.web.bind.annotation.ResponseBody; 8 9 @Controller 10 public class SpringBootController { 11 12 @Autowired 13 private RedisTemplate<String, String> redisTemplate; 14 15 @RequestMapping(value = "/setRedis") 16 @ResponseBody 17 public String setRedis() { 18 this.redisTemplate.opsForValue().set("hello", "world"); 19 return "success"; 20 } 21 22 }
为了避免出现乱码,在存储的数据有可能是字符串、对象等不同的内容,也会有中文等不同编码的数据,所以这里先自定义下Redis的序列化器。
1 package com.demo.config; 2 3 import org.springframework.cache.annotation.CachingConfigurerSupport; 4 import org.springframework.cache.annotation.EnableCaching; 5 import org.springframework.context.annotation.Bean; 6 import org.springframework.context.annotation.Configuration; 7 import org.springframework.data.redis.connection.RedisConnectionFactory; 8 import org.springframework.data.redis.core.RedisTemplate; 9 import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; 10 11 @Configuration 12 @EnableCaching 13 public class RedisConfig extends CachingConfigurerSupport { 14 15 /** 16 * 自定义Redis的序列化器 17 * 18 * @return 19 */ 20 @Bean 21 public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory factory) { 22 RedisTemplate<Object, Object> template = new RedisTemplate<>(); 23 template.setConnectionFactory(factory); 24 Jackson2JsonRedisSerializer<Object> jsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(Object.class); 25 template.setDefaultSerializer(jsonRedisSerializer); 26 return template; 27 } 28 29 }
在集成过程中,一定要注意SpringBoot和Redis不同版本的情况。此次使用的SpringBoot版本是2.X,Redis版本是3.3.0,SpringBoot2.X默认采用lettuce,而SpringBoot1.5默认采用的是jdeis,上面使用的是使用jedis,所以在引入依赖里要排除lettuce。
2、SpringBoot 2.X集成Redis,这里再使用Lettuce来进行操作一遍。springboot-2.2.4.RELEASE没有出错,springboot-2.3.5.RELEASE整合的时候报错了,这里先使用较低版本的。
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.2.4.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 <!--springboot2.X默认使用lettuce连接池,需要引入commons-pool2 --> 43 <dependency> 44 <groupId>org.apache.commons</groupId> 45 <artifactId>commons-pool2</artifactId> 46 </dependency> 47 <!--使用redis需要的依赖 --> 48 <dependency> 49 <groupId>org.springframework.boot</groupId> 50 <artifactId>spring-boot-starter-data-redis</artifactId> 51 </dependency> 52 <dependency> 53 <groupId>org.springframework.data</groupId> 54 <artifactId>spring-data-redis</artifactId> 55 </dependency> 56 <!--使用redis需要的依赖 包含了上面的两个依赖 --> 57 <dependency> 58 <groupId>org.springframework.boot</groupId> 59 <artifactId>spring-boot-starter-data-redis-reactive</artifactId> 60 </dependency> 61 </dependencies> 62 63 <build> 64 <plugins> 65 <plugin> 66 <groupId>org.springframework.boot</groupId> 67 <artifactId>spring-boot-maven-plugin</artifactId> 68 </plugin> 69 </plugins> 70 <resources> 71 <resource> 72 <directory>src/main/resources</directory> 73 <includes> 74 <include>**/*.properties</include> 75 <include>**/*.yml</include> 76 <include>**/*.xml</include> 77 <include>**/*.p12</include> 78 <include>**/*.html</include> 79 <include>**/*.jpg</include> 80 <include>**/*.png</include> 81 </includes> 82 </resource> 83 </resources> 84 </build> 85 86 </project>
Redis缓存方法一:通过 redisTemplate 操作,创建一个公共方法的工具类,如下所示:
1 package com.demo.utils; 2 3 import java.util.List; 4 import java.util.Map; 5 import java.util.Set; 6 import java.util.concurrent.TimeUnit; 7 8 import org.springframework.beans.factory.annotation.Autowired; 9 import org.springframework.data.redis.core.RedisTemplate; 10 import org.springframework.stereotype.Component; 11 import org.springframework.util.CollectionUtils; 12 13 /** 14 * 15 * @author Redis缓存方法一:通过 redisTemplate 操作 16 * 17 */ 18 @Component 19 public class RedisUtils { 20 21 @Autowired 22 private RedisTemplate<String, Object> redisTemplate; 23 24 public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) { 25 this.redisTemplate = redisTemplate; 26 } 27 28 /** 29 * 指定缓存失效时间 30 * 31 * @param key 32 * 键 33 * @param time 34 * 时间(秒) 35 */ 36 public boolean expire(String key, long time) { 37 try { 38 if (time > 0) { 39 redisTemplate.expire(key, time, TimeUnit.SECONDS); 40 } 41 return true; 42 } catch (Exception e) { 43 e.printStackTrace(); 44 return false; 45 } 46 } 47 48 /** 49 * 根据key 获取过期时间 50 * 51 * @param key 52 * 键 不能为null 53 * @return 时间(秒) 返回0代表为永久有效 54 */ 55 public long getExpire(String key) { 56 return redisTemplate.getExpire(key, TimeUnit.SECONDS); 57 } 58 59 /** 60 * 判断key是否存在 61 * 62 * @param key 63 * 键 64 * @return true 存在 false不存在 65 */ 66 public boolean hasKey(String key) { 67 try { 68 return redisTemplate.hasKey(key); 69 } catch (Exception e) { 70 e.printStackTrace(); 71 return false; 72 } 73 } 74 75 /** 76 * 删除缓存 77 * 78 * @param key 79 * 可以传一个值 或多个 80 */ 81 @SuppressWarnings("unchecked") 82 public void del(String... key) { 83 if (key != null && key.length > 0) { 84 if (key.length == 1) { 85 redisTemplate.delete(key[0]); 86 } else { 87 redisTemplate.delete(CollectionUtils.arrayToList(key)); 88 } 89 } 90 } 91 92 // ============================String============================= 93 94 /** 95 * 普通缓存获取 96 * 97 * @param key 98 * 键 99 * @return 值 100 */ 101 public Object get(String key) { 102 return key == null ? null : redisTemplate.opsForValue().get(key); 103 } 104 105 /** 106 * 普通缓存放入 107 * 108 * @param key 109 * 键 110 * @param value 111 * 值 112 * @return true成功 false失败 113 */ 114 public boolean set(String key, Object value) { 115 try { 116 redisTemplate.opsForValue().set(key, value); 117 return true; 118 } catch (Exception e) { 119 e.printStackTrace(); 120 return false; 121 } 122 123 } 124 125 /** 126 * 普通缓存放入并设置时间 127 * 128 * @param key 129 * 键 130 * @param value 131 * 值 132 * @param time 133 * 时间(秒) time要大于0 如果time小于等于0 将设置无限期 134 * @return true成功 false 失败 135 */ 136 public boolean set(String key, Object value, long time) { 137 try { 138 if (time > 0) { 139 redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS); 140 } else { 141 set(key, value); 142 } 143 return true; 144 } catch (Exception e) { 145 e.printStackTrace(); 146 return false; 147 } 148 } 149 150 /** 151 * 递增 152 * 153 * @param key 154 * 键 155 * @param 156 * @return 157 */ 158 public long incr(String key, long delta) { 159 if (delta < 0) { 160 throw new RuntimeException("递增因子必须大于0"); 161 } 162 return redisTemplate.opsForValue().increment(key, delta); 163 } 164 165 /** 166 * 递减 167 * 168 * @param key 169 * 键 170 * @param delta 171 * 要减少几(小于0) 172 * @return 173 */ 174 public long decr(String key, long delta) { 175 if (delta < 0) { 176 throw new RuntimeException("递减因子必须大于0"); 177 } 178 return redisTemplate.opsForValue().decrement(key, -delta); 179 } 180 181 // ================================Map================================= 182 183 /** 184 * HashGet 185 * 186 * @param key 187 * 键 不能为null 188 * @param item 189 * 项 不能为null 190 * @return 值 191 */ 192 public Object hget(String key, String item) { 193 return redisTemplate.opsForHash().get(key, item); 194 } 195 196 /** 197 * 获取hashKey对应的所有键值 198 * 199 * @param key 200 * 键 201 * @return 对应的多个键值 202 */ 203 public Map<Object, Object> hmget(String key) { 204 return redisTemplate.opsForHash().entries(key); 205 } 206 207 /** 208 * HashSet 209 * 210 * @param key 211 * 键 212 * @param map 213 * 对应多个键值 214 * @return true 成功 false 失败 215 */ 216 public boolean hmset(String key, Map<String, Object> map) { 217 try { 218 redisTemplate.opsForHash().putAll(key, map); 219 return true; 220 } catch (Exception e) { 221 e.printStackTrace(); 222 return false; 223 } 224 } 225 226 /** 227 * HashSet 并设置时间 228 * 229 * @param key 230 * 键 231 * @param map 232 * 对应多个键值 233 * @param time 234 * 时间(秒) 235 * @return true成功 false失败 236 */ 237 public boolean hmset(String key, Map<String, Object> map, long time) { 238 try { 239 redisTemplate.opsForHash().putAll(key, map); 240 if (time > 0) { 241 expire(key, time); 242 } 243 return true; 244 } catch (Exception e) { 245 e.printStackTrace(); 246 return false; 247 } 248 } 249 250 /** 251 * 向一张hash表中放入数据,如果不存在将创建 252 * 253 * @param key 254 * 键 255 * @param item 256 * 项 257 * @param value 258 * 值 259 * @return true 成功 false失败 260 */ 261 public boolean hset(String key, String item, Object value) { 262 try { 263 redisTemplate.opsForHash().put(key, item, value); 264 return true; 265 } catch (Exception e) { 266 e.printStackTrace(); 267 return false; 268 } 269 } 270 271 /** 272 * 向一张hash表中放入数据,如果不存在将创建 273 * 274 * @param key 275 * 键 276 * @param item 277 * 项 278 * @param value 279 * 值 280 * @param time 281 * 时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间 282 * @return true 成功 false失败 283 */ 284 public boolean hset(String key, String item, Object value, long time) { 285 try { 286 redisTemplate.opsForHash().put(key, item, value); 287 if (time > 0) { 288 expire(key, time); 289 } 290 return true; 291 } catch (Exception e) { 292 e.printStackTrace(); 293 return false; 294 } 295 } 296 297 /** 298 * 删除hash表中的值 299 * 300 * @param key 301 * 键 不能为null 302 * @param item 303 * 项 可以使多个 不能为null 304 */ 305 public void hdel(String key, Object... item) { 306 redisTemplate.opsForHash().delete(key, item); 307 } 308 309 /** 310 * 判断hash表中是否有该项的值 311 * 312 * @param key 313 * 键 不能为null 314 * @param item 315 * 项 不能为null 316 * @return true 存在 false不存在 317 */ 318 public boolean hHasKey(String key, String item) { 319 return redisTemplate.opsForHash().hasKey(key, item); 320 } 321 322 /** 323 * hash递增 如果不存在,就会创建一个 并把新增后的值返回 324 * 325 * @param key 326 * 键 327 * @param item 328 * 项 329 * @param by 330 * 要增加几(大于0) 331 * @return 332 */ 333 public double hincr(String key, String item, double by) { 334 return redisTemplate.opsForHash().increment(key, item, by); 335 } 336 337 /** 338 * hash递减 339 * 340 * @param key 341 * 键 342 * @param item 343 * 项 344 * @param by 345 * 要减少记(小于0) 346 * @return 347 */ 348 public double hdecr(String key, String item, double by) { 349 return redisTemplate.opsForHash().increment(key, item, -by); 350 } 351 352 // ============================set============================= 353 354 /** 355 * 根据key获取Set中的所有值 356 * 357 * @param key 358 * 键 359 * @return 360 */ 361 public Set<Object> sGet(String key) { 362 try { 363 return redisTemplate.opsForSet().members(key); 364 } catch (Exception e) { 365 e.printStackTrace(); 366 return null; 367 } 368 } 369 370 /** 371 * 根据value从一个set中查询,是否存在 372 * 373 * @param key 374 * 键 375 * @param value 376 * 值 377 * @return true 存在 false不存在 378 */ 379 public boolean sHasKey(String key, Object value) { 380 try { 381 return redisTemplate.opsForSet().isMember(key, value); 382 } catch (Exception e) { 383 e.printStackTrace(); 384 return false; 385 } 386 } 387 388 /** 389 * 将数据放入set缓存 390 * 391 * @param key 392 * 键 393 * @param values 394 * 值 可以是多个 395 * @return 成功个数 396 */ 397 public long sSet(String key, Object... values) { 398 try { 399 return redisTemplate.opsForSet().add(key, values); 400 } catch (Exception e) { 401 e.printStackTrace(); 402 return 0; 403 } 404 } 405 406 /** 407 * 将set数据放入缓存 408 * 409 * @param key 410 * 键 411 * @param time 412 * 时间(秒) 413 * @param values 414 * 值 可以是多个 415 * @return 成功个数 416 */ 417 public long sSetAndTime(String key, long time, Object... values) { 418 try { 419 Long count = redisTemplate.opsForSet().add(key, values); 420 if (time > 0) 421 expire(key, time); 422 return count; 423 } catch (Exception e) { 424 e.printStackTrace(); 425 return 0; 426 } 427 } 428 429 /** 430 * 获取set缓存的长度 431 * 432 * @param key 433 * 键 434 * @return 435 */ 436 public long sGetSetSize(String key) { 437 try { 438 return redisTemplate.opsForSet().size(key); 439 } catch (Exception e) { 440 e.printStackTrace(); 441 return 0; 442 } 443 } 444 445 /** 446 * 移除值为value的 447 * 448 * @param key 449 * 键 450 * @param values 451 * 值 可以是多个 452 * @return 移除的个数 453 */ 454 public long setRemove(String key, Object... values) { 455 try { 456 Long count = redisTemplate.opsForSet().remove(key, values); 457 return count; 458 } catch (Exception e) { 459 e.printStackTrace(); 460 return 0; 461 } 462 } 463 // ===============================list================================= 464 465 /** 466 * 获取list缓存的内容 467 * 468 * @param key 469 * 键 470 * @param start 471 * 开始 472 * @param end 473 * 结束 0 到 -1代表所有值 474 * @return 475 */ 476 public List<Object> lGet(String key, long start, long end) { 477 try { 478 return redisTemplate.opsForList().range(key, start, end); 479 } catch (Exception e) { 480 e.printStackTrace(); 481 return null; 482 } 483 } 484 485 /** 486 * 获取list缓存的长度 487 * 488 * @param key 489 * 键 490 * @return 491 */ 492 public long lGetListSize(String key) { 493 try { 494 return redisTemplate.opsForList().size(key); 495 } catch (Exception e) { 496 e.printStackTrace(); 497 return 0; 498 } 499 } 500 501 /** 502 * 通过索引 获取list中的值 503 * 504 * @param key 505 * 键 506 * @param index 507 * 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推 508 * @return 509 */ 510 public Object lGetIndex(String key, long index) { 511 try { 512 return redisTemplate.opsForList().index(key, index); 513 } catch (Exception e) { 514 e.printStackTrace(); 515 return null; 516 } 517 } 518 519 /** 520 * 将list放入缓存 521 * 522 * @param key 523 * 键 524 * @param value 525 * 值 526 * @param time 527 * 时间(秒) 528 * @return 529 */ 530 public boolean lSet(String key, Object value) { 531 try { 532 redisTemplate.opsForList().rightPush(key, value); 533 return true; 534 } catch (Exception e) { 535 e.printStackTrace(); 536 return false; 537 } 538 } 539 540 /** 541 * 将list放入缓存 542 * 543 * @param key 544 * 键 545 * @param value 546 * 值 547 * @param time 548 * 时间(秒) 549 * @return 550 */ 551 public boolean lSet(String key, Object value, long time) { 552 try { 553 redisTemplate.opsForList().rightPush(key, value); 554 if (time > 0) 555 expire(key, time); 556 return true; 557 } catch (Exception e) { 558 e.printStackTrace(); 559 return false; 560 } 561 } 562 563 /** 564 * 将list放入缓存 565 * 566 * @param key 567 * 键 568 * @param value 569 * 值 570 * @param 571 * @return 572 */ 573 public boolean lSet(String key, List<Object> value) { 574 try { 575 redisTemplate.opsForList().rightPushAll(key, value); 576 return true; 577 } catch (Exception e) { 578 e.printStackTrace(); 579 return false; 580 } 581 } 582 583 /** 584 * 将list放入缓存 585 * 586 * @param key 587 * 键 588 * @param value 589 * 值 590 * @param time 591 * 时间(秒) 592 * @return 593 */ 594 public boolean lSet(String key, List<Object> value, long time) { 595 try { 596 redisTemplate.opsForList().rightPushAll(key, value); 597 if (time > 0) 598 expire(key, time); 599 return true; 600 } catch (Exception e) { 601 e.printStackTrace(); 602 return false; 603 } 604 } 605 606 /** 607 * 根据索引修改list中的某条数据 608 * 609 * @param key 610 * 键 611 * @param index 612 * 索引 613 * @param value 614 * 值 615 * @return 616 */ 617 public boolean lUpdateIndex(String key, long index, Object value) { 618 try { 619 redisTemplate.opsForList().set(key, index, value); 620 return true; 621 } catch (Exception e) { 622 e.printStackTrace(); 623 return false; 624 } 625 } 626 627 /** 628 * 移除N个值为value 629 * 630 * @param key 631 * 键 632 * @param count 633 * 移除多少个 634 * @param value 635 * 值 636 * @return 移除的个数 637 */ 638 public long lRemove(String key, long count, Object value) { 639 try { 640 Long remove = redisTemplate.opsForList().remove(key, count, value); 641 return remove; 642 } catch (Exception e) { 643 e.printStackTrace(); 644 return 0; 645 } 646 } 647 648 }
redis配置类,可以配置一些序列化的操作,如下所示:
1 package com.demo.config; 2 3 import java.lang.reflect.Method; 4 import java.util.HashSet; 5 import java.util.Set; 6 7 import javax.annotation.Resource; 8 9 import org.springframework.cache.CacheManager; 10 import org.springframework.cache.annotation.EnableCaching; 11 import org.springframework.cache.interceptor.KeyGenerator; 12 import org.springframework.context.annotation.Bean; 13 import org.springframework.context.annotation.Configuration; 14 import org.springframework.data.redis.cache.RedisCacheManager; 15 import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; 16 import org.springframework.data.redis.core.RedisTemplate; 17 import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; 18 import org.springframework.data.redis.serializer.RedisSerializer; 19 import org.springframework.data.redis.serializer.StringRedisSerializer; 20 21 import com.fasterxml.jackson.annotation.JsonAutoDetect; 22 import com.fasterxml.jackson.annotation.PropertyAccessor; 23 import com.fasterxml.jackson.databind.ObjectMapper; 24 import com.fasterxml.jackson.databind.ObjectMapper.DefaultTyping; 25 import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator; 26 27 @Configuration 28 @EnableCaching // 开启缓存支持(无此注解,可能无法读取redis配置文件) 29 public class RedisConfig /* extends CachingConfigurerSupport */ { 30 31 @Resource 32 private LettuceConnectionFactory lettuceConnectionFactory; 33 34 /** 35 * 自定义缓存key的生成策略。默认的生成策略是看不懂的(乱码内容) 通过Spring 36 * 的依赖注入特性进行自定义的配置注入并且此类是一个配置类可以更多程度的自定义配置 根据类名+方法名+所有参数的值生成唯一的一个key 37 */ 38 @Bean 39 public KeyGenerator keyGenerator() { 40 return new KeyGenerator() { 41 @Override 42 public Object generate(Object target, Method method, Object... params) { 43 StringBuffer sb = new StringBuffer(); 44 sb.append(target.getClass().getName()); 45 sb.append(method.getName()); 46 for (Object obj : params) { 47 sb.append(obj.toString()); 48 } 49 return sb.toString(); 50 } 51 }; 52 } 53 54 // 缓存管理器 55 @Bean 56 public CacheManager cacheManager() { 57 RedisCacheManager.RedisCacheManagerBuilder builder = RedisCacheManager.RedisCacheManagerBuilder 58 .fromConnectionFactory(lettuceConnectionFactory); 59 @SuppressWarnings("serial") 60 Set<String> cacheNames = new HashSet<String>() { 61 { 62 add("codeNameCache"); 63 } 64 }; 65 builder.initialCacheNames(cacheNames); 66 return builder.build(); 67 } 68 69 @Bean 70 public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory lettuceConnectionFactory) { 71 // 配置 Jackson2JsonRedisSerializer 序列化器,在配置 redisTemplate需要用来做k,v的序列化器 72 // 此种序列化方式结果清晰、容易阅读、存储字节少、速度快,所以推荐更换 73 Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>( 74 Object.class); 75 ObjectMapper om = new ObjectMapper(); 76 om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); 77 // 过期了此方法 78 // om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); 79 80 // 替换方法 81 om.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, DefaultTyping.NON_FINAL); 82 83 // om.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, 84 // ObjectMapper.DefaultTyping.NON_FINAL, 85 // JsonTypeInfo.As.WRAPPER_ARRAY); 86 87 jackson2JsonRedisSerializer.setObjectMapper(om); 88 // 配置redisTemplate 89 RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>(); 90 91 lettuceConnectionFactory.afterPropertiesSet();//必须初始化实例 92 93 redisTemplate.setConnectionFactory(lettuceConnectionFactory); 94 RedisSerializer<?> stringSerializer = new StringRedisSerializer(); 95 redisTemplate.setKeySerializer(stringSerializer);// key序列化 96 redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);// value序列化 97 redisTemplate.setHashKeySerializer(stringSerializer);// Hash key序列化 98 redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);// Hash value序列化 99 redisTemplate.afterPropertiesSet(); 100 return redisTemplate; 101 } 102 103 }
搞个控制类,简单测试一下,如下所示:
1 package com.demo.controller; 2 3 import org.springframework.beans.factory.annotation.Autowired; 4 import org.springframework.stereotype.Controller; 5 import org.springframework.web.bind.annotation.RequestMapping; 6 import org.springframework.web.bind.annotation.ResponseBody; 7 8 import com.demo.utils.RedisUtils; 9 10 @Controller 11 public class SpringBootController { 12 13 @Autowired 14 private RedisUtils redisUtils; 15 16 @RequestMapping(value = "/setRedis") 17 @ResponseBody 18 public String setRedis() { 19 this.redisUtils.set("hello", "world222"); 20 return "success"; 21 } 22 23 }
如果是一个节点ip地址,可以这样配置,如下所示:
1 # Redis的相关配置,主机名称 2 spring.redis.host=192.168.110.140 3 # 端口号 4 spring.redis.port=6379 5 # 认证密码 6 spring.redis.password= 7 # 连接超时时间 8 spring.redis.timeout=1000 9 # 默认数据库 10 spring.redis.database=0 11 # 连接池配置,最大连接数,连接池最大连接数(使用负值表示没有限制) 12 spring.redis.lettuce.pool.max-active=10 13 # 最大维持连接数,连接池中的最大空闲连接 14 spring.redis.lettuce.pool.max-idle=8 15 # 最小维持连接数,连接池中的最小空闲连接 16 spring.redis.lettuce.pool.min-idle=2 17 # 最大等待连接超时时间,连接池最大阻塞等待时间(使用负值表示没有限制) 18 spring.redis.lettuce.pool.max-wait=100
如果是一个三主三从的集群,redis的地址可以这样配置,如下所示:
1 # 集群ip+端口号 2 spring.redis.cluster.nodes[0]=192.168.110.140:7001 3 spring.redis.cluster.nodes[1]=192.168.110.140:7002 4 spring.redis.cluster.nodes[2]=192.168.110.140:7003 5 spring.redis.cluster.nodes[3]=192.168.110.140:7004 6 spring.redis.cluster.nodes[4]=192.168.110.140:7005 7 spring.redis.cluster.nodes[5]=192.168.110.140:7006 8 #密码,若没有,不填写 9 spring.redis.password= 10 #数据库索引(默认为0) 11 spring.redis.database=0 12 # 连接超时时间(毫秒) 13 spring.redis.timeout=6000ms 14 15 spring.redis.cluster.max-redirects=3 16 #连接池最大连接数(使用负值表示没有限制) 17 spring.redis.lettuce.pool.max-active=1000 18 #连接池中的最大空闲连接 19 spring.redis.lettuce.pool.max-idle=10 20 # 连接池中的最小空闲连接 21 spring.redis.lettuce.pool.min-idle=5 22 # 连接池最大阻塞等待时间(使用负值表示没有限制) 23 spring.redis.lettuce.pool.max-wait=-1
如何向Redis里面保存实体类数据呢,首先搞一个实体类,如下所示:
1 package com.demo.po; 2 3 public class UserInfo { 4 5 private Integer userId;// 用户编号 6 7 private String userAccount;// 用户账号 8 9 private String userPw;// 用户密码 10 11 private String userNumber;// 用户学号 12 13 private String userName;// 用户姓名 14 15 private Integer userAge;// 用户年龄 16 17 private String userSex;// 用户性别 18 19 private String userMark;// 用户标识,可以使用一张表,完成管理员和用户 20 21 private String isMoney; 22 23 public Integer getUserId() { 24 return userId; 25 } 26 27 public void setUserId(Integer userId) { 28 this.userId = userId; 29 } 30 31 public String getUserAccount() { 32 return userAccount; 33 } 34 35 public void setUserAccount(String userAccount) { 36 this.userAccount = userAccount; 37 } 38 39 public String getUserPw() { 40 return userPw; 41 } 42 43 public void setUserPw(String userPw) { 44 this.userPw = userPw; 45 } 46 47 public String getUserNumber() { 48 return userNumber; 49 } 50 51 public void setUserNumber(String userNumber) { 52 this.userNumber = userNumber; 53 } 54 55 public String getUserName() { 56 return userName; 57 } 58 59 public void setUserName(String userName) { 60 this.userName = userName; 61 } 62 63 public Integer getUserAge() { 64 return userAge; 65 } 66 67 public void setUserAge(Integer userAge) { 68 this.userAge = userAge; 69 } 70 71 public String getUserSex() { 72 return userSex; 73 } 74 75 public void setUserSex(String userSex) { 76 this.userSex = userSex; 77 } 78 79 public String getUserMark() { 80 return userMark; 81 } 82 83 public void setUserMark(String userMark) { 84 this.userMark = userMark; 85 } 86 87 public String getIsMoney() { 88 return isMoney; 89 } 90 91 public void setIsMoney(String isMoney) { 92 this.isMoney = isMoney; 93 } 94 95 @Override 96 public String toString() { 97 return "UserInfo [userId=" + userId + ", userAccount=" + userAccount + ", userPw=" + userPw + ", userNumber=" 98 + userNumber + ", userName=" + userName + ", userAge=" + userAge + ", userSex=" + userSex 99 + ", userMark=" + userMark + ", isMoney=" + isMoney + "]"; 100 } 101 102 }
搞一个控制层,测试一下保存和获取的功能,如下所示:
1 package com.demo.controller; 2 3 import org.springframework.beans.factory.annotation.Autowired; 4 import org.springframework.stereotype.Controller; 5 import org.springframework.web.bind.annotation.RequestMapping; 6 import org.springframework.web.bind.annotation.ResponseBody; 7 8 import com.demo.po.UserInfo; 9 import com.demo.utils.RedisUtils; 10 11 @Controller 12 public class SpringBootController { 13 14 @Autowired 15 private RedisUtils redisUtils; 16 17 public static final String REDIS_USER_ID_KEY_PREFIX = "userInfo::id-"; 18 19 @RequestMapping(value = "/setRedis") 20 @ResponseBody 21 public String setRedis() { 22 UserInfo userInfo = new UserInfo(); 23 userInfo.setUserId(1008611); 24 userInfo.setUserAccount("张三"); 25 userInfo.setUserName("张姗姗"); 26 userInfo.setUserAge(28); 27 userInfo.setUserNumber("1415925549"); 28 userInfo.setUserPw("123456"); 29 userInfo.setUserSex("男"); 30 this.redisUtils.set(REDIS_USER_ID_KEY_PREFIX + 1008611, userInfo); 31 32 UserInfo info = (UserInfo) this.redisUtils.get(REDIS_USER_ID_KEY_PREFIX + 1008611); 33 System.out.println(info); 34 this.redisUtils.set("hello", "world333"); 35 return "success"; 36 } 37 38 }
效果,如下所示:
3、Redis对象序列化操作在实际项目开发中,使用RedisTemplate操作Redis数据库不仅可以方便地进行命令的操作,还可以结合对象序列化操作,实现对象的保存。定义对象的序列化配置类,以实现RedisSerializer接口。
1 package com.demo.config; 2 3 import org.springframework.core.convert.converter.Converter; 4 import org.springframework.core.serializer.support.DeserializingConverter; 5 import org.springframework.core.serializer.support.SerializingConverter; 6 import org.springframework.data.redis.serializer.RedisSerializer; 7 import org.springframework.data.redis.serializer.SerializationException; 8 9 public class RedisObjectSerializer implements RedisSerializer<Object> { 10 11 // 为了进行对象和字节数组的转换,应该准备两个转换器 12 private Converter<Object, byte[]> serializingConverter = new SerializingConverter(); 13 private Converter<byte[], Object> deserializingConverter = new DeserializingConverter(); 14 // 定义一个空数组 15 private static final byte[] EMPTY_BYTE_ARRAY = new byte[0]; 16 17 /** 18 * 反序列化 19 */ 20 @Override 21 public Object deserialize(byte[] data) throws SerializationException { 22 // 如果没有对象内容信息 23 if (data == null || data.length == 0) { 24 return null; 25 } 26 return this.deserializingConverter.convert(data); 27 } 28 29 /** 30 * 序列化 31 */ 32 @Override 33 public byte[] serialize(Object obj) throws SerializationException { 34 // 如果没有要序列化的对象,则返回一个空数组 35 if (obj == null) { 36 return EMPTY_BYTE_ARRAY; 37 } 38 // 将对象变为字节数组 39 return this.serializingConverter.convert(obj); 40 } 41 42 }
要让建立的对象序列化管理类生效,还需要建立一个RedisTemplate的配置类,这里直接修改之前配置的类,将键值序列化的时候使用自定义的序列化和反序列化。
1 package com.demo.config; 2 3 import java.lang.reflect.Method; 4 import java.util.HashSet; 5 import java.util.Set; 6 7 import javax.annotation.Resource; 8 9 import org.springframework.cache.CacheManager; 10 import org.springframework.cache.annotation.EnableCaching; 11 import org.springframework.cache.interceptor.KeyGenerator; 12 import org.springframework.context.annotation.Bean; 13 import org.springframework.context.annotation.Configuration; 14 import org.springframework.data.redis.cache.RedisCacheManager; 15 import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; 16 import org.springframework.data.redis.core.RedisTemplate; 17 import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; 18 import org.springframework.data.redis.serializer.RedisSerializer; 19 import org.springframework.data.redis.serializer.StringRedisSerializer; 20 21 import com.fasterxml.jackson.annotation.JsonAutoDetect; 22 import com.fasterxml.jackson.annotation.PropertyAccessor; 23 import com.fasterxml.jackson.databind.ObjectMapper; 24 import com.fasterxml.jackson.databind.ObjectMapper.DefaultTyping; 25 import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator; 26 27 @Configuration 28 @EnableCaching // 开启缓存支持(无此注解,可能无法读取redis配置文件) 29 public class RedisConfig /* extends CachingConfigurerSupport */ { 30 31 @Resource 32 private LettuceConnectionFactory lettuceConnectionFactory; 33 34 /** 35 * 自定义缓存key的生成策略。默认的生成策略是看不懂的(乱码内容) 通过Spring 36 * 的依赖注入特性进行自定义的配置注入并且此类是一个配置类可以更多程度的自定义配置 根据类名+方法名+所有参数的值生成唯一的一个key 37 */ 38 @Bean 39 public KeyGenerator keyGenerator() { 40 return new KeyGenerator() { 41 @Override 42 public Object generate(Object target, Method method, Object... params) { 43 StringBuffer sb = new StringBuffer(); 44 sb.append(target.getClass().getName()); 45 sb.append(method.getName()); 46 for (Object obj : params) { 47 sb.append(obj.toString()); 48 } 49 return sb.toString(); 50 } 51 }; 52 } 53 54 // 缓存管理器 55 @Bean 56 public CacheManager cacheManager() { 57 RedisCacheManager.RedisCacheManagerBuilder builder = RedisCacheManager.RedisCacheManagerBuilder 58 .fromConnectionFactory(lettuceConnectionFactory); 59 @SuppressWarnings("serial") 60 Set<String> cacheNames = new HashSet<String>() { 61 { 62 add("codeNameCache"); 63 } 64 }; 65 builder.initialCacheNames(cacheNames); 66 return builder.build(); 67 } 68 69 @Bean 70 public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory lettuceConnectionFactory) { 71 // 配置 Jackson2JsonRedisSerializer 序列化器,在配置 redisTemplate需要用来做k,v的序列化器 72 // 此种序列化方式结果清晰、容易阅读、存储字节少、速度快,所以推荐更换 73 Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>( 74 Object.class); 75 ObjectMapper om = new ObjectMapper(); 76 om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); 77 // 过期了此方法 78 // om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); 79 80 // 替换方法 81 om.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, DefaultTyping.NON_FINAL); 82 83 // om.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, 84 // ObjectMapper.DefaultTyping.NON_FINAL, 85 // JsonTypeInfo.As.WRAPPER_ARRAY); 86 87 jackson2JsonRedisSerializer.setObjectMapper(om); 88 // 配置redisTemplate 89 RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>(); 90 91 lettuceConnectionFactory.afterPropertiesSet();//必须初始化实例 92 93 // 设置lettuceConnectionFactory工厂 94 redisTemplate.setConnectionFactory(lettuceConnectionFactory); 95 RedisSerializer<?> stringSerializer = new StringRedisSerializer(); 96 // redisTemplate.setKeySerializer(stringSerializer);// key序列化 97 // redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);// value序列化 98 99 // 使用自定义的序列化和反序列化操作 100 redisTemplate.setKeySerializer(new StringRedisSerializer());// key序列化 101 redisTemplate.setValueSerializer(new RedisObjectSerializer());// value序列化 102 103 redisTemplate.setHashKeySerializer(stringSerializer);// Hash key序列化 104 redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);// Hash value序列化 105 redisTemplate.afterPropertiesSet(); 106 return redisTemplate; 107 } 108 109 }
创建一个实体类,实现序列化接口,不然调用的时候会报错的哦,如下所示:
1 package com.demo.po; 2 3 import java.io.Serializable; 4 5 public class UserInfo implements Serializable { 6 7 /** 8 * 9 */ 10 private static final long serialVersionUID = 1L; 11 12 private Integer userId;// 用户编号 13 14 private String userAccount;// 用户账号 15 16 private String userPw;// 用户密码 17 18 private String userNumber;// 用户学号 19 20 private String userName;// 用户姓名 21 22 private Integer userAge;// 用户年龄 23 24 private String userSex;// 用户性别 25 26 private String userMark;// 用户标识,可以使用一张表,完成管理员和用户 27 28 private String isMoney; 29 30 public Integer getUserId() { 31 return userId; 32 } 33 34 public void setUserId(Integer userId) { 35 this.userId = userId; 36 } 37 38 public String getUserAccount() { 39 return userAccount; 40 } 41 42 public void setUserAccount(String userAccount) { 43 this.userAccount = userAccount; 44 } 45 46 public String getUserPw() { 47 return userPw; 48 } 49 50 public void setUserPw(String userPw) { 51 this.userPw = userPw; 52 } 53 54 public String getUserNumber() { 55 return userNumber; 56 } 57 58 public void setUserNumber(String userNumber) { 59 this.userNumber = userNumber; 60 } 61 62 public String getUserName() { 63 return userName; 64 } 65 66 public void setUserName(String userName) { 67 this.userName = userName; 68 } 69 70 public Integer getUserAge() { 71 return userAge; 72 } 73 74 public void setUserAge(Integer userAge) { 75 this.userAge = userAge; 76 } 77 78 public String getUserSex() { 79 return userSex; 80 } 81 82 public void setUserSex(String userSex) { 83 this.userSex = userSex; 84 } 85 86 public String getUserMark() { 87 return userMark; 88 } 89 90 public void setUserMark(String userMark) { 91 this.userMark = userMark; 92 } 93 94 public String getIsMoney() { 95 return isMoney; 96 } 97 98 public void setIsMoney(String isMoney) { 99 this.isMoney = isMoney; 100 } 101 102 @Override 103 public String toString() { 104 return "UserInfo [userId=" + userId + ", userAccount=" + userAccount + ", userPw=" + userPw + ", userNumber=" 105 + userNumber + ", userName=" + userName + ", userAge=" + userAge + ", userSex=" + userSex 106 + ", userMark=" + userMark + ", isMoney=" + isMoney + "]"; 107 } 108 109 }
还使用上面的控制类即可,这里进行简单的测试一下,如下所示:
1 package com.demo.controller; 2 3 import org.springframework.beans.factory.annotation.Autowired; 4 import org.springframework.stereotype.Controller; 5 import org.springframework.web.bind.annotation.RequestMapping; 6 import org.springframework.web.bind.annotation.ResponseBody; 7 8 import com.demo.po.UserInfo; 9 import com.demo.utils.RedisUtils; 10 11 @Controller 12 public class SpringBootController { 13 14 @Autowired 15 private RedisUtils redisUtils; 16 17 public static final String REDIS_USER_ID_KEY_PREFIX = "userInfo::id-"; 18 19 @RequestMapping(value = "/setRedis") 20 @ResponseBody 21 public String setRedis() { 22 UserInfo userInfo = new UserInfo(); 23 userInfo.setUserId(1008611); 24 userInfo.setUserAccount("张三🌂"); 25 userInfo.setUserName("张姗姗"); 26 userInfo.setUserAge(28); 27 userInfo.setUserNumber("1415925549"); 28 userInfo.setUserPw("123456"); 29 userInfo.setUserSex("男"); 30 this.redisUtils.set(REDIS_USER_ID_KEY_PREFIX + 1008611, userInfo); 31 32 UserInfo info = (UserInfo) this.redisUtils.get(REDIS_USER_ID_KEY_PREFIX + 1008611); 33 System.out.println(info); 34 this.redisUtils.set("hello", "world333"); 35 return "success"; 36 } 37 38 }
演示效果,从redis集群里面获取到的也是正常的,但是redis里面直接观看还是需要转义才可以看具体值的,如下所示: