Redis缓存

@EnableCaching
@SpringBootApplication
public class TestApplication {

	public static void main(String[] args) {
		SpringApplication.run(TestApplication.class, args);
	}
	
}
@Configuration
public class RedisConfig extends CachingConfigurerSupport {

    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) {
    	RedisTemplate redisTemplate = new RedisTemplate<>();
		// 使用fastJson序列化
		FastJsonRedisSerializer fastJsonRedisSerializer = new FastJsonRedisSerializer<>(Object.class);
		// value值的序列化采用fastJsonRedisSerializer
		redisTemplate.setValueSerializer(fastJsonRedisSerializer);
		redisTemplate.setHashValueSerializer(fastJsonRedisSerializer);
		// key的序列化采用StringRedisSerializer
		redisTemplate.setKeySerializer(new StringRedisSerializer());
		redisTemplate.setHashKeySerializer(new StringRedisSerializer());
		redisTemplate.setConnectionFactory(redisConnectionFactory);
		return redisTemplate;
    }
    
}
@Slf4j
public class FastJsonRedisSerializer implements RedisSerializer {

	public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
	
	ObjectMapper mapper = new ObjectMapper();
	
    private Class clazz;
    
    public FastJsonRedisSerializer(Class clazz) {
        super();
        this.clazz = clazz;
    }
    
    @Override
    public byte[] serialize(T t) throws SerializationException {
        if (t == null) {
            return new byte[0];
        }
        try {
			return mapper.writeValueAsString(t).getBytes(DEFAULT_CHARSET);
		} catch (JsonProcessingException e) {
			log.error("{}", e.getMessage());
		}
        return new byte[0];
    }
    
    @Override
    public T deserialize(byte[] bytes) throws SerializationException {
        if (bytes == null || bytes.length <= 0) {
            return null;
        }
        String str = new String(bytes, DEFAULT_CHARSET);
        try {
			return mapper.readValue(str, clazz);
		} catch (IOException e) {
			log.error("{}", e.getMessage());
		}
        return null;
    }
    
}

application.properties配置文件

spring.redis.host=127.0.0.1
spring.redis.password=
spring.redis.port=6379
spring.redis.database=0
spring.redis.pool.max-active=8
spring.redis.pool.max-wait=-1
spring.redis.pool.max-idle=8
spring.redis.pool.min-idle=0
spring.cache.redis.time-to-live=0
spring.cache.type=redis

测试和测试结果

@Autowired
RedisTemplate redisTemplate;

Map map = new HashMap<>();
map.put("hello", "world");
redisTemplate.opsForHash().putAll("t2", map);
Object obj = redisTemplate.opsForHash().get("t2", "hello");
log.info("{}", obj);
Map entries = redisTemplate.opsForHash().entries("t2");
for (Map.Entry entry : entries.entrySet()) {
	log.info("{}:{}", entry.getKey(), entry.getValue());
}
2024-01-15 15:49:02 [restartedMain] INFO  cn.hwd.TestRunner - world 
2024-01-15 15:49:02 [restartedMain] INFO  cn.hwd.TestRunner - hello:world

Redis缓存_第1张图片

你可能感兴趣的:(Redis,redis)