重写 RedisTemplate的bean
package com.example.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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;
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory connectionFactory)
{
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
//为redisTemplate设置redis连接工厂
redisTemplate.setConnectionFactory(connectionFactory);
//设置key的序列化方式
GenericJackson2JsonRedisSerializer serializer = new GenericJackson2JsonRedisSerializer();
redisTemplate.setKeySerializer(RedisSerializer.string());
redisTemplate.setHashKeySerializer(RedisSerializer.string());
//设置value的序列化方式
redisTemplate.setValueSerializer(serializer);
redisTemplate.setHashValueSerializer(serializer);
return redisTemplate;
}
}
如果不是在springboot的环境下,需要导入包
<!--jackson-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.5</version>
</dependency>
在StringRedisTemplate的例子
package com.example;
import com.example.entity.User;
import com.fasterxml.jackson.core.JsonProcessingException;
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.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import com.fasterxml.jackson.databind.ObjectMapper;
@SpringBootTest
class RedisLettuceApplicationTests {
@Autowired
private RedisTemplate<String,Object> redisTemplate;
@Autowired
private StringRedisTemplate stringRedisTemplate;
private static final ObjectMapper objectMapper = new ObjectMapper();
@Test
void contextLoads() throws JsonProcessingException {
User user = new User("ccccc",15); //对象
String s = objectMapper.writeValueAsString(user); //实体对象转为json对象,也可以送fastjson
stringRedisTemplate.opsForHash().put("cc:user:4","user",s);
Object o = stringRedisTemplate.opsForHash().get("cc:user:4", "user");
stringRedisTemplate.opsForValue().set("wr",s);
String s1 = stringRedisTemplate.opsForValue().get("wr");
User user1 = objectMapper.readValue(o.toString(), User.class); //需要实体的默认构造函数
System.out.println(user1);
}
}