- 更改redis配置文件 开启redis对外的权限
图一如果没注释的话,只能本机客户端连接到服务端。
图二是设置连接redis时密码
- Redis免费的客户端工具Another Redis Desktop Manager gitee下载地址
连接redis服务
- springBoot项目 maven导入依赖 (注意版本要兼容 我这springboot项目是2.2.4)
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<version>2.2.4.RELEASE</version>
</dependency>
4.编写springBoot的application.yml配置文件
4. 测试(StringRedisTemplate是RedisTemplate的一个子类,操作的键和值都是字符串类型。如果要操作对象,就需要使用RedisTemplate,操作RedisTemplate存值和取值时,都会对键和值进行序列化(默认方式JdkSerializationRedisSerializer),也就是说要存对象的话,对象就得实现序列化接口Serializable)
5.RedisTemplate存储对象
6.由于RedisTemplate操作时会将key和value都进行序列化,key的序列化也许会带来不便,以下配置可修改key的默认序列化为字符串序列化(StringRedisSerializer),即存的key是什么,redis中就放对应的key字符串。
6.SpringBoot前后端交互一般都是Json形式。我们可以自己配置RedisTemplate的bean,开启缓存,且将值序列化方式设为Json。
@EnableCaching//开启缓存
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
//RedisTemplate对象
RedisTemplate<String, Object> template = new RedisTemplate<>();
//字符串序列化
RedisSerializer<String> stringRedisSerializer = new StringRedisSerializer();
//json序列化
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
template.setConnectionFactory(factory);
//设置key序列化方式为字符串
template.setKeySerializer(stringRedisSerializer);
//设置value序列化方式为json
template.setValueSerializer(jackson2JsonRedisSerializer);
//设置hash的key序列化方式为字符串
template.setHashKeySerializer(stringRedisSerializer);
//设置hash的value序列化方式为json
template.setHashValueSerializer(jackson2JsonRedisSerializer);
return template;
}
@Bean
public CacheManager cacheManager(RedisConnectionFactory factory) {
RedisSerializer<String> redisSerializer = new StringRedisSerializer();
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
//解决查询缓存转换异常的问题
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
// 配置序列化(解决乱码的问题),缓存过期时间600秒
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofSeconds(600))
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
.disableCachingNullValues();
RedisCacheManager cacheManager = RedisCacheManager.builder(factory)
.cacheDefaults(config)
.build();
return cacheManager;
}
}