1、在pom.xml
文件中引入Redis
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<version>2.1.6.RELEASE</version>
</dependency>
aaplcation.yml
文件配置Redis
spring:
datasource:
url: jdbc:mysql://localhost:3306/springboot_cache?serverTimezone=UTC
username: root
password: 123456
redis:
host: 127.0.0.1
port: 6379
2、Redis简单的测试
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootAdvanceCacheApplicationTests {
@Autowired
EmployeeMapper employeeMapper;
@Autowired
StringRedisTemplate stringRedisTemplate; //操作 K-V都是字符串
@Autowired
RedisTemplate redisTemplate; //K-V都是对象
@Test
public void test(){
stringRedisTemplate.opsForValue().append("msg","hello");
}
@Test
public void test01(){
String msg = stringRedisTemplate.opsForValue().get("msg");
System.out.printf("=="+msg);
}
}
3、将Redis应用到我们业务中
新建一个RddisConfig类
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
@Bean
public KeyGenerator keyGenerator() {
return new KeyGenerator() {
@Override
public Object generate(Object target, Method method, Object... params) {
StringBuilder sb = new StringBuilder();
sb.append(target.getClass().getName());
sb.append(method.getName());
for (Object obj : params) {
sb.append(obj.toString());
}
return sb.toString();
}
};
}
}
Service
层代码
@Cacheable(cacheNames = {"emp"})
public Employee getEmpById(Integer id){
System.out.println("查询"+id+"号员工");
Employee employee = employeeMapper.getEmpById(id);
return employee;
}
记得在实体类上实现序列化!!!
public class Employee implements Serializable
不然会报
org.springframework.data.redis.serializer.SerializationException: Cannot serialize; nested exception is org.springframework.core.serializer.support.SerializationFailedException: Failed to serialize object using DefaultSerializer; nested exception is java.lang.IllegalArgumentException:DefaultSerializer requires a Serializable payload but received an object of type[com.bx.cloud.common.auth.component.AuthSession]
然后运行程序
我们发现存入Redis中是我们一些看不懂的,那么我们来将结果以
json
的方式存到Redis中
参考这篇文章:https://blog.csdn.net/caojidasabi/article/details/83059642
在我们上面编写的RedisConfig类中添加我们自定义的cacheManager方法
@Configuration
public class MyRedisConfig {
@Bean
public RedisTemplate<Object, Employee> empRedisTemplate(
RedisConnectionFactory redisConnectionFactory)
throws UnknownHostException {
RedisTemplate<Object, Employee> template = new RedisTemplate<Object, Employee>();
template.setConnectionFactory(redisConnectionFactory);
Jackson2JsonRedisSerializer<Employee> jsonRedisSerializer = new Jackson2JsonRedisSerializer<Employee>(Employee.class);
template.setDefaultSerializer(jsonRedisSerializer);
return template;
}
}
//自定义cacheManager缓存管理器
@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);
//配置序列化(解决乱码的问题)
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ZERO)
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
.disableCachingNullValues();
RedisCacheManager cacheManager = RedisCacheManager.builder(factory)
.cacheDefaults(config)
.build();
return cacheManager;
}
然后就会发现Redis中存储的是json形式的啦~