前言:
据我目前的了解, Redis就是一个管理缓存的工具, 对缓存进行操作
1、启用Redis服务
切换路径: cd /d F:\Redis
开启Redis: redis-server.exe redis.windows.conf
1、导入相关依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<!-- <version>2.2.2.RELEASE</version> -->
</dependency>
这里我把版本注释掉, 让springboot自动适配版本, 否则会报错。
2、application.yml配置
spring:
redis:
host: localhost
port: 6379
配置好端口号和IP地址
3、储存数据时序列化的配置
package com.example.config;
import java.net.UnknownHostException;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
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;
@Configuration
public class MyRedisConfg {
@Bean
public RedisTemplate<Object, User> redisTemplate(
RedisConnectionFactory redisConnectionFactory)
throws UnknownHostException {
System.out.println("成功更改序列化器...");
RedisTemplate<Object, User> template = new RedisTemplate<Object, User>();
template.setConnectionFactory(redisConnectionFactory);
template.setDefaultSerializer(new Jackson2JsonRedisSerializer<User>(User.class));
return template;
}
@Bean
public RedisCacheManager empManager(RedisTemplate<Object, Employee> template) {
RedisCacheManager cacheManager = new RedisCacheManager(template);
cacheManager.setUsePrefix(true);
return cacheManager;
}
}
当你需要储存对象时, redisTemplate会使用默认的序列化方法, 从而储存到Redis数据库中的对象数据是一串像乱码一样的东西, 无法查看, 所以这里要更改它的默认序列化方法, template.setDefaultSerializer(new Jackson2JsonRedisSerializer(User.class));, 随后有一个 cacheManager Redis缓存管理来接收这个 template 对象。这样的话, 储存到Redis数据库中的对象就以json格式来呈现了。
4、测试类
@Test
public void test02(){
//储存字符串
stringRedisTemplate.opsForValue().append("msg", "abc");
//储存对象
redisTemplate.opsForValue().set("user2", user);
}
注意:User对象在储存时要实现序列化, 否则可能会报错。
打开这个Redis软件查看保存是否成功
拓展:
@Cacheable(cacheNames = {"emp"}, key="#id"/*, keyGenerator="cacheKey", condition = "#id>1 and #root.methodName eq 'getEmp' ", unless = "#id==2"*/)
public Employee getEmp(int id){
System.out.println("查询...");
return employeeMapper.get(id);
}
运行一下被缓存注解标记的方法, 得到的缓存也会储存在Redis数据库中。