pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>wsd</groupId><artifactId>redis-study01</artifactId><version>1.0-SNAPSHOT</version><properties><!-- 设置 Java 版本 --><maven.compiler.source>17</maven.compiler.source><maven.compiler.target>17</maven.compiler.target></properties><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.5.7</version><relativePath></relativePath></parent><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency><dependency><groupId>org.apache.commons</groupId><artifactId>commons-pool2</artifactId><version>2.9.0</version></dependency><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.13.0</version></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>
springboot配置文件(application.yaml):
spring:redis:host: 192.168.88.130port: 6379password: wsdrootlettuce:pool:max-active: 5min-idle: 2max-idle: 3max-wait: 300ms
package com.wsd;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;@SpringBootApplication
public class SpringDataRedis {public static void main(String[] args) {ConfigurableApplicationContext context = SpringApplication.run(SpringDataRedis.class, args);//配置连接工厂RedisConnectionFactory connectionFactory = context.getBean(RedisConnectionFactory.class);RedisTemplate<String,Object> redisTemplate = new RedisTemplate<>();redisTemplate.setConnectionFactory(connectionFactory);//配置序列化器redisTemplate.setKeySerializer(RedisSerializer.string());redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());//确保在配置完成后调用 afterPropertiesSet() 方法,以便确保 RedisTemplate 的正确初始化。这样可以避免出现 template not initialized 的异常。redisTemplate.afterPropertiesSet();redisTemplate.opsForValue().set("name","罗小白");redisTemplate.opsForValue().set("age","5");String name = (String) redisTemplate.opsForValue().get("name");String age = (String) redisTemplate.opsForValue().get("age");StringBuilder s = new StringBuilder();s.append("name:");s.append(name);s.append("\n");s.append("age:");s.append(age);System.out.println(s);}
}