1.Redis:
客户端工具:
jedis | 指令型工具,简单易用 |
lettuce | redis官方认可,opsForValue、opsForHash |
redission | 解决了分布式的各种问题 比如锁 |
redis data | 官方推荐,封装了jedis、lettuce |
使用方式:
1.引入包:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- redis连接池-->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
2.引入redis序列化工具
@Bean
public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory){
//创建RedisTemplate对象
RedisTemplate<String,Object> template = new RedisTemplate<>();
//设置连接工厂
template.setConnectionFactory(redisConnectionFactory);
//创建json序列化工具
GenericJackson2JsonRedisSerializer jsonRedisSerializer = new GenericJackson2JsonRedisSerializer();
//设置key的序列化
template.setKeySerializer(RedisSerializer.string());
template.setHashKeySerializer(RedisSerializer.string());
//设置value的序列化
template.setValueSerializer(jsonRedisSerializer);
template.setHashKeySerializer(jsonRedisSerializer);
return template;
3.测试:
@SpringBootTest
class RedisDemoApplicationTests {
@Autowired
private RedisTemplate redisTemplate;
@Test
void contextLoads() {
redisTemplate.opsForValue().set("name","赵哥");
Object name = redisTemplate.opsForValue().get("name");
System.out.println(name);
}
@Test
public void setSaveUser(){
redisTemplate.opsForValue().set("user:100",new User("赵哥",30));
User o = (User) redisTemplate.opsForValue().get("user:100");
System.out.println("o = "+o);
}
redis存储内容:
{
"@class": "com.itjk.pojo.User",
"name": "赵哥",
"age": 30
}
简化存储值
@SpringBootTest
class RedisStringTests {
// redis 自带的序列化器
@Autowired
private StringRedisTemplate stringRedisTemplate;
private static final ObjectMapper mapper = new ObjectMapper();
@Test
void contextLoads() {
stringRedisTemplate.opsForValue().set("name","赵哥");
Object name = stringRedisTemplate.opsForValue().get("name");
System.out.println(name);
}
@Test
public void setSaveUser() throws JsonProcessingException {
// 创建对象
User user = new User("赵哥", 30);
String json = mapper.writeValueAsString(user);
stringRedisTemplate.opsForValue().set("user:200",json);
String jsonUser = stringRedisTemplate.opsForValue().get("user:200");
User o = mapper.readValue(jsonUser, User.class);
System.out.println("o = "+o);
}
@Test
public void setHash(){
stringRedisTemplate.opsForHash().put("user:300","name","赵哥");
stringRedisTemplate.opsForHash().put("user:300","age","30");
Map<Object, Object> entries = stringRedisTemplate.opsForHash().entries("user:300");
System.out.println("entries= "+entries);
}
}
redis存储内容:
{
"name": "赵哥",
"age": 30
}
标签:name,redis,opsForValue,Redis,user,使用,stringRedisTemplate,User
From: https://www.cnblogs.com/xxs-oao/p/17575723.html