一 操作步骤
1.1导入Spring Data Redis 的maven坐标
1.2配置Redis数据源
redis:
host: localhost
port: 6379
database: 0
1.3编写配置类,创建RedisTemplate对象
package com.sky.config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@Configuration
@Slf4j
public class RedisConfiguration {
@Bean
/**
* 配置并返回一个RedisTemplate实例
* 该实例用于与Redis数据库进行交互和操作,通过本方法配置连接工厂和序列化方式
*
* @param redisConnectionFactory Redis连接工厂,用于建立与Redis服务器的连接
* @return 返回配置好的RedisTemplate实例,用于执行对Redis数据库的操作
*/
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
log.info("开始创建RedisTemplate实例...");
// 创建一个RedisTemplate实例
RedisTemplate<String, Object> template = new RedisTemplate<>();
// 设置Redis连接工厂,指定如何连接到Redis服务器
template.setConnectionFactory(redisConnectionFactory);
// 设置键的序列化方式为StringRedisSerializer,确保键以字符串形式存储和读取
template.setKeySerializer(new StringRedisSerializer());
// 设置值的序列化方式为GenericJackson2JsonRedisSerializer,确保值以JSON形式序列化和反序列化
template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
// 返回配置好的RedisTemplate实例
return template;
}
}
1.4通过RedisTemplate对象操作Redis
在测试类中操作Redis
package com.sky.test;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.*;
@SpringBootTest
public class SpringDataRedisTest {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
@Test
public void testRedis() {
redisTemplate.opsForValue().set("hello", "world");
System.out.println(redisTemplate.opsForValue().get("hello"));
redisTemplate.opsForValue().set("name", "张三");
System.out.println(redisTemplate.opsForValue().get("name"));
}
}