1、下载redis
地址:https://pan.baidu.com/s/1WWKnHhpboESA0vwXwbpGNg
提取码:r9ze
2、解压后直接运行redis-server.exe
连接命令:redis-cli -h 地址 -p 6379 -a 密码
本地先测试下,运行redis-cli.exe,测试读写数据,ok没问题
3、引入maven依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
4、redis配置类
/**
* description redis配置类
*
* @author yanzy
* @date 2019/5/6 14:06
*/
@Configuration
public class RedisConfiguration {
@Bean
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
RedisTemplate<Object, Object> template = new RedisTemplate<>();
template.setConnectionFactory(connectionFactory);
//使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值
Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper mapper = new ObjectMapper();
mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
serializer.setObjectMapper(mapper);
// 使用StringRedisSerializer来序列化和反序列化redis的key值
template.setValueSerializer(serializer);
template.setKeySerializer(new StringRedisSerializer());
template.afterPropertiesSet();
return template;
}
}
5、代码测试
@Autowired
private RedisTemplate<Object, Object> redisTemplate;
@GetMapping("/test")
public void test() {
// 存入缓存
redisTemplate.opsForValue().set("haha", "哈哈哈哈哈");
// 查询
Object key = redisTemplate.opsForValue().get("haha");
System.out.println(key);
}