yml文件配置:
redis:
database: 0
port: 6379
host: localhost
password:
connect-timeout: 1000
lettuce:
pool:
max-active: 8
max-idle: 8
max-wait: -1
min-idle: 0
配置类如下:
package com.eccom.asset.config;
import org.springframework.cache.annotation.CacheConfig;
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.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
/**
* @author : 一只小海猪
* @date : 20:16 2021/11/21
* redis配置类,实现序列化
*/
//@Configuration //这里需要使用配置注解,如果用CacheConfig会导致扫描不到这个配置类
@CacheConfig
public class RedisConfig {
@Bean
public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){
RedisTemplate<String,Object> redisTemplate = new RedisTemplate<>();
//key序列化
redisTemplate.setKeySerializer(new StringRedisSerializer());
//对象序列化
redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
//hash序列化
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
//注入连接工厂
redisTemplate.setConnectionFactory(redisConnectionFactory);
return redisTemplate;
}
}
这里需要使用配置注解@Configuration,如果用@CacheConfig会导致扫描不到这个配置类。
加上或者将@CacheConfig注解改为@Configuration就好了。