在web开发中缓存是我们应对高并发不可或缺的一部分,其中Redis也是缓存的最佳解决方法。
本章介绍SpringBoot中使用Redis的方法。
1. 添加Redis依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2. 添加Redis配置参数
spring.redis.host=localhost
spring.redis.port=6379
#Redis的密码,不使用密码请注解
#spring.redis.password=123456
3. RedisTemplate配置类
由于RedisTemplate存储的是二进制不方便查阅,所以我们需要配置类对其进行转换一下。代码如下:
package com.example.yxjc.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
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;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@Configuration
public class RedisConfiguration {
@Bean(name="redisTemplate")
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory);
// 使用Jackson2JsonRedisSerialize 替换默认序列化
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
// 设置value的序列化规则和 key的序列化规则
redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
}
4.使用RedisTemplate
在需要使用的地方注入ReidsTemplate
@Autowired
RedisTemplate redisTemplate;
5.常用方法
- redisTemplate.opsForValue() 操作String
- redisTemplate.opsForList() 操作LIST
- redisTemplate.opsForSet() 操作SET
- redisTemplate.opsForHash() 操作HASH
- redisTemplate.opsForZSet() 操作ZSET