1.接缓存代码
springboot 缓存1_简单实现_spring boot缓存管理的实现步骤-CSDN博客
1.1 pom添加redis依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<version>2.0.2.RELEASE</version>
</dependency>
2.测试application,text中
package com.cc.springboot;
import com.cc.springboot.entities.User;
import com.cc.springboot.service.UserService;
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 java.util.List;
@SpringBootTest
class Springboot13cacheApplicationTests {
//操作复杂的类型,自定义id
@Autowired
RedisTemplate redisTemplate;
//自定义的json序列化器
@Autowired
RedisTemplate jsonRedisTemplate;
//针对的是操作字符串
@Autowired
StringRedisTemplate stringRedisTemplate;
@Autowired
UserService userService;
/* stringRedisTemplate.opsForValue();//操作字符串
stringRedisTemplate.opsForList();//操作list
stringRedisTemplate.opsForSet(); //操作set
stringRedisTemplate.opsForZSet();//操作zset
stringRedisTemplate.opsForHash();//操作Hash*/
@Test
void contextLoads() {
// String演示
// stringRedisTemplate.opsForValue().set("name","cc");
String name = stringRedisTemplate.opsForValue().get("name");
System.out.println(name);//cc
// List演示
// stringRedisTemplate.opsForList().leftPush("mylist","a");
// stringRedisTemplate.opsForList().leftPushAll("mylist","b","c","d");
List<String> mylist = stringRedisTemplate.opsForList().range("mylist", 0, -1);
System.out.println(mylist); //[d, c, b, a]
}
@Test
public void testRedis(){
User user = userService.getUserById(12);
// 保存的数据对象必须序列化 implements Serializable
//因为redisTemplate默认使用的jdk序列化
// redisTemplate.opsForValue().set("user",user);
User user1 = (User) redisTemplate.opsForValue().get("user");
System.out.println(user1);
jsonRedisTemplate.opsForValue().set("suer2",user);
}
}
发现使用redisTemplate存入redis中的格式很乱,若想要转换成json格式需要进一步设置,因为redisTemplate默认使用的是jdk序列化。
转化json格式
1.Ctrl+N搜索RedisAutoConfiguration复制这个方法RedisTemplate
2.创建config/RedisConfig,将复制的方法粘贴,修改方法template.setDefaultSerializer(new Jackson2JsonRedisSerializer(Object.class));
点击setDefaultSerializer查看 ,形参上Ctrl+H看到子类方法
package com.cc.springboot.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.Jackson2JsonRedisSerializer;
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<Object, Object> jsonRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<Object, Object> template = new RedisTemplate<>();
template.setDefaultSerializer(new Jackson2JsonRedisSerializer(Object.class));
template.setConnectionFactory(redisConnectionFactory);
return template;
}
}
3.测试类中引入使用