一、自动配置redis的使用
- 首先,显然是导入redis相关的starter 依赖
<!--缓存redis的依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
- 配置redis
# Redis数据库索引(默认为0)
spring.redis.database=0
# Redis服务器地址
spring.redis.host=127.0.0.1
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active=200
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait=-1
# 连接池中的最大空闲连接
spring.redis.pool.max-idle=10
# 连接池中的最小空闲连接
spring.redis.pool.min-idle=0
# 连接超时时间(毫秒)
spring.redis.timeout=1000
- 当导入依赖后springboot会检查当前是否有RedisTemplate的配置,如果没有的话,它会自动配置两个可访问redis的自动配置,注意你配置的一定要是redisTemplate 这个名字,否则它依然会自动生成。
@Configuration
@ConditionalOnClass(RedisOperations.class)
@EnableConfigurationProperties(RedisProperties.class)
@Import({LettuceConnectionConfiguration.class,JedisConnectionConfiguration.class})
public class RedisAutoConfiguration {
@Bean
@ConditionalOnMissingBean(name = "redisTemplate")
public RedisTemplate<Object, Object> redisTemplate(
RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
RedisTemplate<Object, Object> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
return template;
}
@Bean
@ConditionalOnMissingBean
public StringRedisTemplate stringRedisTemplate(
RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
StringRedisTemplate template = new StringRedisTemplate();
template.setConnectionFactory(redisConnectionFactory);
return template;
}
}
3.2 如上两个配置是springboot发现没有自定义配置时自动配置的,可直接使用
@Autowired
RedisTemplate redisTemplate;
@Test
public void test6(){
redisTemplate.opsForValue().append("k2","v2");
}
@Autowired
StringRedisTemplate stringRedisTemplate;
@Test
public void test7(){
stringRedisTemplate.opsForValue().set("k3","v3");
}
结果发现有一个是我们肉眼无法识别的形式存在,这个就是redisTemplate的序列化机制,虽然提供了自动配置但是也有很多的限制:
redisTemplate:k-v 都是object类型的数据
stringRedisTemplate:k-v 都是String类型的数据
127.0.0.1:6379> keys *
1) "\xac\xed\x00\x05t\x00\x02k2"
2) "k3"
二、自定义配置RedisTemplate,存入json数据格式
- 自定义配置类
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){
RedisTemplate<Object, Object> template = new RedisTemplate<Object, Object>();
template.setConnectionFactory(redisConnectionFactory);
//自定义序列化规则
Jackson2JsonRedisSerializer<Object> json = new Jackson2JsonRedisSerializer<Object>(Object.class);
template.setDefaultSerializer(json);
return template;
}
//缓存数据-----------工程是在上一篇缓存介绍的基础上
@Autowired
RedisTemplate<Object,Object> redisTemplate;
@Autowired
StudentService studentService;
@Test
public void test8(){
com.cjy.mq.bean.Student student = studentService.getStudentById(13);
redisTemplate.opsForValue().set("stu-13",student);
}
//Parameter 0 of method cacheManager in com.cjy.mq.config.RedisConfig
// required a bean of type ‘org.springframework.data.redis.core.RedisTemplate’ that could not be found.-----注意如果启动报这个错误肯能由于跟默认的redisTemplate 冲突了,导致无法注入,需要修改redisTemplate 名称,不能一致可修改 xxxredisTemplate
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){
RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
template.setConnectionFactory(redisConnectionFactory);
//自定义序列化规则--这种问题解决了但是还会有其他问题,后序介绍
Jackson2JsonRedisSerializer<Object> json = new Jackson2JsonRedisSerializer<Object>(Object.class);
template.setDefaultSerializer(json);
redis数据库结果:发现没有这样的话会有两条数据存在,一条是我们指定的key,一条是stu缓存组件的默认规则生成的key。
- 但是通过http访问的话,结合@Cacheable 缓存数据虽然是json格式,但是当我们需要使用缓存的时候,无法加载,下面就来测试一下
@CacheConfig(cacheNames = "stu")
@Service
public class StudentServiceImpl implements StudentService {
@Cacheable() //value 与 cacheNames 同一个意思点进cacheable注解可看到
@Override
public Student getStudentById(Integer id) {
Student student = studentMapper.getStudentById(id);
log.info("查询"+id+" 号学生信息:" + student);
return student;
}
}
测试链接: http://localhost:8080/stu/6 查询id为6 的数据并缓存,下面是缓存结果
注意:当我们再次访问时,返回结果无法转换。如果我们注释掉json格式转换的代码,使用默认序列化方式,则又可以了。
{
“timestamp”: 1552748314528,
“status”: 500,
“error”: “Internal Server Error”,
“exception”: “java.lang.ClassCastException”,
“message”: “java.util.LinkedHashMap cannot be cast to com.cjy.mq.bean.Student”,
“path”: “/stu/6”
}
当我修改配置类的名称时:redisTemplate–>zdyredisTemplate,发现自动注入redisTemplate时是扫描这个方法名称的,当没有这个id的bean则会自动注入一个,下面我修改了这个方法的名称,它默认我们是没有创建的则会在注入一个redisTemplate ,这是我在测试发现它可以在http中正常访问,但是写入缓存时依然是我我们肉眼无法识别的数据,这就跟它的缓存管理器有关了
//修改方法名与默认的redisTemplate 不冲突
@Bean
public RedisTemplate<Object, Object> zdyredisTemplate(RedisConnectionFactory redisConnectionFactory){
RedisTemplate<Object, Object> template = new RedisTemplate<Object, Object>();
template.setConnectionFactory(redisConnectionFactory);
//自定义序列化规则
Jackson2JsonRedisSerializer<Object> json = new Jackson2JsonRedisSerializer<Object>(Object.class);
template.setDefaultSerializer(json);
return template;
}
查看缓存管理器:RedisCacheManager
public class RedisCacheManager extends AbstractTransactionSupportingCacheManager {
private final Log logger;
private final RedisOperations redisOperations; //主要查看这个
private boolean usePrefix;
private RedisCachePrefix cachePrefix;
private boolean loadRemoteCachesOnStartup;
private boolean dynamic;
private long defaultExpiration;
private Map<String, Long> expires;
private Set<String> configuredCacheNames;
private final boolean cacheNullValues;
public RedisCacheManager(RedisOperations redisOperations) {
this(redisOperations, Collections.emptyList());
}
}
查看:redisOperations,发现它是一个接口,那么我们就去看看谁实现了它,下面就是他的实现类
RedisOperations (org.springframework.data.redis.core)
-----RedisTemplate (org.springframework.data.redis.core)
-----StringRedisTemplate (org.springframework.data.redis.core)
- 重写缓存管理器注入指定redistemplate,如果RedisTemplate<Object, Student>依然是这种类型,或者名字时 redisTemplate 那么和默认的一样效果,缓存读取转换类型失败。
3.1为指定数据类型定制缓存管理器
@Bean
public RedisTemplate<Object, Student> zdyredisTemplate(RedisConnectionFactory redisConnectionFactory){
RedisTemplate<Object, Student> template = new RedisTemplate<Object, Student>();
template.setConnectionFactory(redisConnectionFactory);
//自定义序列化规则
Jackson2JsonRedisSerializer<Student> json = new Jackson2JsonRedisSerializer<Student>(Student.class);
template.setDefaultSerializer(json);
return template;
}
//与缓存管理器绑定
@Bean
public RedisCacheManager cacheManager(RedisTemplate<Object,Student> zdyredisTemplate){
RedisCacheManager redisCacheManager = new RedisCacheManager(zdyredisTemplate);
redisCacheManager.setUsePrefix(true);
return redisCacheManager;
}
3.2 测试结果:http://localhost:8080/stu/20,缓存插入,查询都正常,但是这个方式的话,就将缓存的数据类型定死了,查询别的数据类型使用此缓存管理器则一样无法类型转换。
3.3 测试另一种类型: http://localhost:8080/class/3
{
“timestamp”: 1552751527196,
“status”: 500,
“error”: “Internal Server Error”,
“exception”: “org.springframework.data.redis.serializer.SerializationException”,
“message”: “Could not read JSON: Unrecognized field “className” (class com.cjy.mq.bean.Student), not marked as ignorable (6 known properties: “classId”, “stuEmail”, “id”, “stuName”, “stuAge”, “stuHeight”])\n at [Source: [B@1c6cb942; line: 1, column: 22] (through reference chain: com.cjy.mq.bean.Student[“className”]); nested exception is com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field “className” (class com.cjy.mq.bean.Student), not marked as ignorable (6 known properties: “classId”, “stuEmail”, “id”, “stuName”, “stuAge”, “stuHeight”])\n at [Source: [B@1c6cb942; line: 1, column: 22] (through reference chain: com.cjy.mq.bean.Student[“className”])”,
“path”: “/class/3”
}
4 如果再配置另一个reidsTemplate,与CacheManager的话则需要指定一个默认的缓存管理器。
在为class类创建一个缓存管理器,则需要指定默认缓存管理器
@Bean
public RedisTemplate<Object, Class> claredisTemplate(RedisConnectionFactory redisConnectionFactory){
RedisTemplate<Object, Class> template = new RedisTemplate<Object, Class>();
template.setConnectionFactory(redisConnectionFactory);
//自定义序列化规则
Jackson2JsonRedisSerializer<Class> json = new Jackson2JsonRedisSerializer<Class>(Student.class);
template.setDefaultSerializer(json);
return template;
}
//与缓存管理器绑定
@Bean
public RedisCacheManager classCacheManager(RedisTemplate<Object,Class> claredisTemplate){
RedisCacheManager redisCacheManager = new RedisCacheManager(claredisTemplate);
redisCacheManager.setUsePrefix(true);
return redisCacheManager;
}
指定默认缓存管理器:
@Primary //默认缓存管理器
@Bean
public RedisCacheManager cacheManager(RedisTemplate<Object,Student> zdyredisTemplate){
RedisCacheManager redisCacheManager = new RedisCacheManager(zdyredisTemplate);
redisCacheManager.setUsePrefix(true);
return redisCacheManager;
}
指定所缓存所使用的缓存管理器:
@Service
@CacheConfig(cacheNames = "cla",cacheManager = "classCacheManager")
public class ClassServiceImpl implements ClassService {
@Autowired
ClassMapper classMapper;
@Cacheable
@Override
public Class getClassById(Integer id) {
Class cla = classMapper.getClassById(id);
return cla;
}
}
如果为每个缓存类型配置一个缓存管理器,template则与@cacheable使用结合时就是肉眼可以识别的json数据,但是但是这样的过就比较麻烦。
一个redis使用API封装博客:
https://www.cnblogs.com/zeng1994/p/03303c805731afc9aa9c60dbbd32a323.html