SpringBoot2.x配置使用Redis
pom文件中引入:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
启动类标注:@EnableCaching
application.properties:
spring.redis.host=0.0.0.0 #redis所在的服务器ip地址
SpringBoot2.x的Reids配置模板
目的:将缓存数据的Key存为String类型,Value则以json的格式存储在redis中,在读取缓存时,同样返回json格式
@Configuration
public class MyRedisConfig {
/*
SpringBoot2.x的ReidsCacheManager自定义配置方法
缓存之后,key会多一个前缀,默认是将CacheName作为key的前缀
*/
@Bean
public RedisCacheManager redisCacheManager(RedisConnectionFactory connectionFactory) {
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()
// 缓存有效期60s
//.entryTtl(Duration.ofSeconds(60))
// 设置key序列化
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
// 设置value序列化
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
// 不缓存null值
.disableCachingNullValues();
RedisCacheManager cacheManager = RedisCacheManager.builder(connectionFactory)
.cacheDefaults(config)
.build();
System.out.println("ReidsCacheManager自定义配置方法被调用了...");
return cacheManager;
}
}
写一个Controller进行测试:
@Mapper
public interface DepartmentMapper {
@Select("select * from department where id = #{id}")
public Department getDeptById(Integer id);
}
@Service
public class DeptService {
@Resource
private DepartmentMapper departmentMapper;
@Cacheable(cacheNames = "dept")
public Department getDeptById(Integer id){
System.out.println("查询的部门是:"+id);
return departmentMapper.getDeptById(id);
}
@RestController
public class DeptController {
@Resource
private DeptService deptService;
@GetMapping("/dept/{id}")
public Department getDept(@PathVariable("id") Integer id) {
return deptService.getDeptById(id);
}
}